Last active
November 1, 2023 08:08
-
-
Save squalvj/58200838e7d3b1c6771070558718c02f to your computer and use it in GitHub Desktop.
This function convert integer like 1000000 into 1M, 1K, etc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
1000