Skip to content

Instantly share code, notes, and snippets.

@squalvj
Last active November 1, 2023 08:08
Show Gist options
  • Save squalvj/58200838e7d3b1c6771070558718c02f to your computer and use it in GitHub Desktop.
Save squalvj/58200838e7d3b1c6771070558718c02f to your computer and use it in GitHub Desktop.
This function convert integer like 1000000 into 1M, 1K, etc
function nFormatter(num, digits) {
var si = [
{ value: 1, symbol: "" },
{ value: 1E3, symbol: "K" },
{ value: 1E6, symbol: "M" },
{ value: 1E9, symbol: "G" },
{ value: 1E12, symbol: "T" },
{ value: 1E15, symbol: "P" },
{ value: 1E18, symbol: "E" }
];
var rx = /\.0+$|(\.[0-9]*[1-9])0+$/;
var i;
// for negative value is work
for (i = si.length - 1; i > 0; i--) {
if (Math.abs(num) >= si[i].value) {
break;
}
}
return (num / si[i].value).toFixed(digits).replace(rx, "$1") + si[i].symbol;
}
@YulmanAgros
Copy link

1000

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment