Created
March 28, 2021 06:08
-
-
Save Izzur/0e635f0a2e2d026a2210546630c94c94 to your computer and use it in GitHub Desktop.
Javascript Commarization
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 https://gist.github.com/MartinMuzatko/1060fe584d17c7b9ca6e | |
const commarize = (n) => { | |
if (n >= 1e3) { | |
const units = [" thousand", " million", " billion", " trillion"]; | |
let unit = Math.floor((n.toFixed(0).length - 1) / 3) * 3; | |
const num = (n / ("1e" + unit)).toFixed(2); | |
const unitname = units[Math.floor(unit / 3) - 1]; | |
return num + unitname; | |
} | |
return n.toLocaleString(); | |
}; | |
// commarize(123456789); => "123.46 million" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment