2021-01-29 14:36:21 +01:00
|
|
|
import { formatNumber } from '@angular/common'
|
|
|
|
import { Inject, LOCALE_ID, Pipe, PipeTransform } from '@angular/core'
|
2017-12-01 14:46:22 +01:00
|
|
|
|
2020-08-11 16:50:00 +02:00
|
|
|
// Thanks: https://github.com/danrevah/ngx-pipes/blob/master/src/ng-pipes/pipes/math/bytes.ts
|
2017-12-01 14:46:22 +01:00
|
|
|
|
2017-12-04 11:17:08 +01:00
|
|
|
@Pipe({ name: 'myNumberFormatter' })
|
2017-12-01 14:46:22 +01:00
|
|
|
export class NumberFormatterPipe implements PipeTransform {
|
|
|
|
|
2021-01-13 09:15:43 +01:00
|
|
|
/**
|
|
|
|
* @param x number
|
|
|
|
* @param n number of decimals to get (defaults to 1, needs to be >= 1)
|
|
|
|
*/
|
|
|
|
static getDecimalForNumber (x: number, n = 1) {
|
|
|
|
const v = x.toString().split('.')
|
|
|
|
const f = v[1] || ''
|
|
|
|
if (f.length > n) return +f.substr(0, n)
|
|
|
|
return +f
|
|
|
|
}
|
|
|
|
|
2021-01-29 14:36:21 +01:00
|
|
|
private dictionary: Array<{max: number, type: string}> = [
|
|
|
|
{ max: 1000, type: '' },
|
|
|
|
{ max: 1000000, type: 'K' },
|
|
|
|
{ max: 1000000000, type: 'M' }
|
|
|
|
]
|
2022-04-05 14:03:52 +02:00
|
|
|
|
2021-01-29 14:36:21 +01:00
|
|
|
constructor (@Inject(LOCALE_ID) private localeId: string) {}
|
|
|
|
|
2017-12-01 14:46:22 +01:00
|
|
|
transform (value: number) {
|
|
|
|
const format = this.dictionary.find(d => value < d.max) || this.dictionary[this.dictionary.length - 1]
|
2021-01-13 09:15:43 +01:00
|
|
|
const calc = value / (format.max / 1000)
|
|
|
|
const integralPart = Math.floor(calc)
|
|
|
|
const decimalPart = NumberFormatterPipe.getDecimalForNumber(calc)
|
2017-12-01 14:46:22 +01:00
|
|
|
|
2021-01-13 09:15:43 +01:00
|
|
|
return integralPart < 10 && decimalPart > 0
|
2021-01-29 14:36:21 +01:00
|
|
|
? formatNumber(parseFloat(`${integralPart}.${decimalPart}`), this.localeId) + format.type
|
2021-01-13 09:15:43 +01:00
|
|
|
: `${integralPart}${format.type}`
|
2017-12-01 14:46:22 +01:00
|
|
|
}
|
|
|
|
}
|