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