Skip to content

Instantly share code, notes, and snippets.

@Izzur
Created March 28, 2021 06:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Izzur/0e635f0a2e2d026a2210546630c94c94 to your computer and use it in GitHub Desktop.
Save Izzur/0e635f0a2e2d026a2210546630c94c94 to your computer and use it in GitHub Desktop.
Javascript Commarization
// 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