]>
Commit | Line | Data |
---|---|---|
68018040 | 1 | import { formatNumber } from '@angular/common' |
2 | import { Inject, LOCALE_ID, Pipe, PipeTransform } from '@angular/core' | |
9bf9d2a5 | 3 | |
94676e63 | 4 | // Thanks: https://github.com/danrevah/ngx-pipes/blob/master/src/ng-pipes/pipes/math/bytes.ts |
9bf9d2a5 | 5 | |
be447678 | 6 | @Pipe({ name: 'myNumberFormatter' }) |
9bf9d2a5 | 7 | export class NumberFormatterPipe implements PipeTransform { |
9bf9d2a5 | 8 | |
22078471 RK |
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] || '' | |
7dcd7d81 | 16 | if (f.length > n) return +f.substring(0, n) |
22078471 RK |
17 | return +f |
18 | } | |
19 | ||
7dcd7d81 | 20 | private dictionary: Array<{ max: number, type: string }> = [ |
68018040 | 21 | { max: 1000, type: '' }, |
22 | { max: 1000000, type: 'K' }, | |
23 | { max: 1000000000, type: 'M' } | |
24 | ] | |
384ba8b7 | 25 | |
68018040 | 26 | constructor (@Inject(LOCALE_ID) private localeId: string) {} |
27 | ||
9bf9d2a5 C |
28 | transform (value: number) { |
29 | const format = this.dictionary.find(d => value < d.max) || this.dictionary[this.dictionary.length - 1] | |
22078471 RK |
30 | const calc = value / (format.max / 1000) |
31 | const integralPart = Math.floor(calc) | |
32 | const decimalPart = NumberFormatterPipe.getDecimalForNumber(calc) | |
9bf9d2a5 | 33 | |
22078471 | 34 | return integralPart < 10 && decimalPart > 0 |
68018040 | 35 | ? formatNumber(parseFloat(`${integralPart}.${decimalPart}`), this.localeId) + format.type |
22078471 | 36 | : `${integralPart}${format.type}` |
9bf9d2a5 C |
37 | } |
38 | } |