Add ShortNumberPipe for formatting large numbers with suffixes; include unit tests for pipe functionality

This commit is contained in:
Christian Werner 2025-10-22 02:57:20 +02:00
parent e14420420f
commit 081ab589f3
2 changed files with 41 additions and 0 deletions

View File

@ -0,0 +1,8 @@
import { ShortNumberPipe } from './short-number.pipe';
describe('ShortNumberPipe', () => {
it('create an instance', () => {
const pipe = new ShortNumberPipe();
expect(pipe).toBeTruthy();
});
});

View 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}`;
}
}