1 import { formatNumber } from '@angular/common'
2 import { Inject, LOCALE_ID, Pipe, PipeTransform } from '@angular/core'
4 // Thanks: https://github.com/danrevah/ngx-pipes/blob/master/src/ng-pipes/pipes/math/bytes.ts
6 @Pipe({ name: 'myNumberFormatter' })
7 export class NumberFormatterPipe implements PipeTransform {
11 * @param n number of decimals to get (defaults to 1, needs to be >= 1)
13 static getDecimalForNumber (x: number, n = 1) {
14 const v = x.toString().split('.')
16 if (f.length > n) return +f.substr(0, n)
20 private dictionary: Array<{max: number, type: string}> = [
21 { max: 1000, type: '' },
22 { max: 1000000, type: 'K' },
23 { max: 1000000000, type: 'M' }
25 constructor (@Inject(LOCALE_ID) private localeId: string) {}
27 transform (value: number) {
28 const format = this.dictionary.find(d => value < d.max) || this.dictionary[this.dictionary.length - 1]
29 const calc = value / (format.max / 1000)
30 const integralPart = Math.floor(calc)
31 const decimalPart = NumberFormatterPipe.getDecimalForNumber(calc)
33 return integralPart < 10 && decimalPart > 0
34 ? formatNumber(parseFloat(`${integralPart}.${decimalPart}`), this.localeId) + format.type
35 : `${integralPart}${format.type}`