X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=client%2Fsrc%2Fapp%2Fshared%2Fshared-main%2Fangular%2Fnumber-formatter.pipe.ts;h=00cfbc692b441dc88ea22d8d309ec4bf06693818;hb=d0fbc9fd0a29c37f3ff9b99030351e90b276fe7d;hp=8a0756a36adfe342e4691400aec705681205c240;hpb=67ed6552b831df66713bac9e672738796128d33f;p=github%2FChocobozzz%2FPeerTube.git diff --git a/client/src/app/shared/shared-main/angular/number-formatter.pipe.ts b/client/src/app/shared/shared-main/angular/number-formatter.pipe.ts index 8a0756a36..00cfbc692 100644 --- a/client/src/app/shared/shared-main/angular/number-formatter.pipe.ts +++ b/client/src/app/shared/shared-main/angular/number-formatter.pipe.ts @@ -1,19 +1,38 @@ -import { Pipe, PipeTransform } from '@angular/core' +import { formatNumber } from '@angular/common' +import { Inject, LOCALE_ID, Pipe, PipeTransform } from '@angular/core' -// Thanks: https://github.com/danrevah/ngx-pipes/blob/master/src/pipes/math/bytes.ts +// Thanks: https://github.com/danrevah/ngx-pipes/blob/master/src/ng-pipes/pipes/math/bytes.ts @Pipe({ name: 'myNumberFormatter' }) export class NumberFormatterPipe implements PipeTransform { - private dictionary: Array<{max: number, type: string}> = [ + + /** + * @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.substring(0, n) + return +f + } + + private dictionary: { max: number, type: string }[] = [ { max: 1000, type: '' }, { max: 1000000, type: 'K' }, { max: 1000000000, type: 'M' } ] + constructor (@Inject(LOCALE_ID) private localeId: string) {} + transform (value: number) { const format = this.dictionary.find(d => value < d.max) || this.dictionary[this.dictionary.length - 1] - const calc = Math.floor(value / (format.max / 1000)) + const calc = value / (format.max / 1000) + const integralPart = Math.floor(calc) + const decimalPart = NumberFormatterPipe.getDecimalForNumber(calc) - return `${calc}${format.type}` + return integralPart < 10 && decimalPart > 0 + ? formatNumber(parseFloat(`${integralPart}.${decimalPart}`), this.localeId) + format.type + : `${integralPart}${format.type}` } }