Last active
August 24, 2017 07:35
-
-
Save Bizunow/112864743b573d51f9d2b4d67bdce6c9 to your computer and use it in GitHub Desktop.
[JS number formater] #js
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
// From StackOverflow: | |
// https://stackoverflow.com/questions/9461621/how-to-format-a-number-as-2-5k-if-a-thousand-or-more-otherwise-900-in-javascrip | |
function nFormatter(num, digits) { | |
var si = [ | |
{ value: 1E18, symbol: "E" }, | |
{ value: 1E15, symbol: "P" }, | |
{ value: 1E12, symbol: "T" }, | |
{ value: 1E9, symbol: "G" }, | |
{ value: 1E6, symbol: "M" }, | |
{ value: 1E3, symbol: "k" } | |
], rx = /\.0+$|(\.[0-9]*[1-9])0+$/, i; | |
for (i = 0; i < si.length; i++) { | |
if (num >= si[i].value) { | |
return (num / si[i].value).toFixed(digits).replace(rx, "$1") + si[i].symbol; | |
} | |
} | |
return parseFloat(num).toFixed(digits).replace(rx, "$1"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment