]>
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] || '' | |
16 | if (f.length > n) return +f.substr(0, n) | |
17 | return +f | |
18 | } | |
19 | ||
68018040 | 20 | private dictionary: Array<{max: number, type: string}> = [ |
21 | { max: 1000, type: '' }, | |
22 | { max: 1000000, type: 'K' }, | |
23 | { max: 1000000000, type: 'M' } | |
24 | ] | |
25 | constructor (@Inject(LOCALE_ID) private localeId: string) {} | |
26 | ||
9bf9d2a5 C |
27 | transform (value: number) { |
28 | const format = this.dictionary.find(d => value < d.max) || this.dictionary[this.dictionary.length - 1] | |
22078471 RK |
29 | const calc = value / (format.max / 1000) |
30 | const integralPart = Math.floor(calc) | |
31 | const decimalPart = NumberFormatterPipe.getDecimalForNumber(calc) | |
9bf9d2a5 | 32 | |
22078471 | 33 | return integralPart < 10 && decimalPart > 0 |
68018040 | 34 | ? formatNumber(parseFloat(`${integralPart}.${decimalPart}`), this.localeId) + format.type |
22078471 | 35 | : `${integralPart}${format.type}` |
9bf9d2a5 C |
36 | } |
37 | } |