Created
April 22, 2019 14:02
-
-
Save ufhy/740d833ad85d4e45b07d4683535b50dc to your computer and use it in GitHub Desktop.
Format a number as 2.5K if a thousand or more, otherwise 900
This file contains hidden or 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 (i = si.length - 1; i > 0; i--) { | |
if (num >= si[i].value) { | |
break; | |
} | |
} | |
return (num / si[i].value).toFixed(digits).replace(rx, "$1") + si[i].symbol; | |
} | |
/* | |
* Tests | |
*/ | |
var tests = [ | |
{ num: 1234, digits: 1 }, | |
{ num: 100000000, digits: 1 }, | |
{ num: 299792458, digits: 1 }, | |
{ num: 759878, digits: 1 }, | |
{ num: 759878, digits: 0 }, | |
{ num: 123, digits: 1 }, | |
{ num: 123.456, digits: 1 }, | |
{ num: 123.456, digits: 2 }, | |
{ num: 123.456, digits: 4 } | |
]; | |
var i; | |
for (i = 0; i < tests.length; i++) { | |
console.log("nFormatter(" + tests[i].num + ", " + tests[i].digits + ") = " + nFormatter(tests[i].num, tests[i].digits)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://stackoverflow.com/questions/9461621/format-a-number-as-2-5k-if-a-thousand-or-more-otherwise-900