34 lines
952 B
TypeScript
34 lines
952 B
TypeScript
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}`;
|
|
}
|
|
|
|
}
|