I used a ranges
array for the magnitude levels, and this is how the code turned out to be:
const ranges = [{
divider: 1E3,
suffix: 'K'
}, {
divider: 1E6,
suffix: 'M'
}, {
divider: 1E9,
suffix: 'B'
}];
function formatNumber(input) {
for (let index = ranges.length - 1; index >= 0; index--) {
if (input > ranges[index].divider) {
let quotient = input / ranges[index].divider;
if (quotient < 10) {
quotient = Math.floor(quotient * 10) / 10;
} else {
quotient = Math.floor(quotient);
}
return quotient.toString() + ranges[index].suffix;
}
}
return input.toString();
}
And this is how it looks like as an Angular pipe:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'formatNumberShortSuffix'
})
export class FormatNumberShortSuffixPipe implements PipeTransform {
readonly ranges = [
{ divider: 1E3, suffix: 'K' },
{ divider: 1E6, suffix: 'M' },
{ divider: 1E9, suffix: 'B' }
];
transform(input: number): string {
for (let index = this.ranges.length - 1; index >= 0; index--) {
if (input > this.ranges[index].divider) {
let quotient = input / this.ranges[index].divider;
if (quotient < 10) {
quotient = Math.floor(quotient * 10) / 10;
} else {
quotient = Math.floor(quotient);
}
return quotient.toString() + this.ranges[index].suffix;
}
}
return input.toString();
}
}