Add ShortNumberPipe for formatting large numbers with suffixes; include unit tests for pipe functionality
This commit is contained in:
parent
e14420420f
commit
081ab589f3
@ -0,0 +1,8 @@
|
|||||||
|
import { ShortNumberPipe } from './short-number.pipe';
|
||||||
|
|
||||||
|
describe('ShortNumberPipe', () => {
|
||||||
|
it('create an instance', () => {
|
||||||
|
const pipe = new ShortNumberPipe();
|
||||||
|
expect(pipe).toBeTruthy();
|
||||||
|
});
|
||||||
|
});
|
||||||
33
src/angular/frontend/src/app/pipes/short-number.pipe.ts
Normal file
33
src/angular/frontend/src/app/pipes/short-number.pipe.ts
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
import { Pipe, PipeTransform } from '@angular/core';
|
||||||
|
|
||||||
|
@Pipe({
|
||||||
|
name: 'shortNumber',
|
||||||
|
pure: true
|
||||||
|
})
|
||||||
|
export class ShortNumberPipe implements PipeTransform {
|
||||||
|
|
||||||
|
private readonly suffixes = ['k', 'M', 'G', 'T', 'P', 'E'];
|
||||||
|
|
||||||
|
transform(input: number, maxDecimals: number = 0): string {
|
||||||
|
|
||||||
|
if (Number.isNaN(input)) {
|
||||||
|
return 'NaN';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input < 1000) {
|
||||||
|
return input.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
const exp = Math.floor(Math.log(input) / Math.log(1000));
|
||||||
|
const fixed = (input / Math.pow(1000, exp)).toFixed(maxDecimals + 1);
|
||||||
|
const split = fixed.split('.');
|
||||||
|
const integer = split[0];
|
||||||
|
const decimal = split.length > 1 ? (+(+('0.' + split[1])).toFixed(maxDecimals + 1)).toString().slice(2) : null;
|
||||||
|
const d = decimal && decimal.length > maxDecimals ? decimal.slice(0, maxDecimals) : decimal;
|
||||||
|
const sliced = integer + (d ? '.' + d : '');
|
||||||
|
const suffix = this.suffixes[exp - 1];
|
||||||
|
|
||||||
|
return `${sliced} ${suffix}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user