Skip to content

Instantly share code, notes, and snippets.

@nnitsoft
Last active January 8, 2020 20:09
Show Gist options
  • Save nnitsoft/2cb391069a7cb249d9e13a67c7dff80a to your computer and use it in GitHub Desktop.
Save nnitsoft/2cb391069a7cb249d9e13a67c7dff80a to your computer and use it in GitHub Desktop.
Display number in billion, million, thousand using custom pipe in angular, medium blog, https://medium.com/@nimishgoel056/display-number-in-billion-million-thousand-using-custom-pipe-in-angular-b95bf388350a
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'numberSuffix'
})
export class NumberSuffixPipe implements PipeTransform {
transform(input: any, args?: any): any {
let exp;
const suffixes = ['K', 'M', 'B', 'T', 'P', 'E'];
const isNagtiveValues = input < 0;
if (Number.isNaN(input) || (input < 1000 && input >= 0) || !this.isNumeric(input) || (input < 0 && input > -1000)) {
if (!!args && this.isNumeric(input) && !(input < 0) && input != 0) {
return input.toFixed(args);
} else {
return input;
}
}
if (!isNagtiveValues) {
exp = Math.floor(Math.log(input) / Math.log(1000));
return (input / Math.pow(1000, exp)).toFixed(args) + suffixes[exp - 1];
} else {
input = input * -1;
exp = Math.floor(Math.log(input) / Math.log(1000));
return (input * -1 / Math.pow(1000, exp)).toFixed(args) + suffixes[exp - 1];
}
}
isNumeric(value): boolean {
if (value < 0) value = value * -1;
if (/^-{0,1}\d+$/.test(value)) {
return true;
} else if (/^\d+\.\d+$/.test(value)) {
return true;
} else {
return false;
}
}
// https://medium.com/@nimishgoel056/display-number-in-billion-million-thousand-using-custom-pipe-in-angular-b95bf388350a
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment