Skip to content

Instantly share code, notes, and snippets.

@alphaolomi
Created March 19, 2022 14:10
Show Gist options
  • Select an option

  • Save alphaolomi/e79f2afbfd4ec494904a10d067a33006 to your computer and use it in GitHub Desktop.

Select an option

Save alphaolomi/e79f2afbfd4ec494904a10d067a33006 to your computer and use it in GitHub Desktop.
Number with commas (JS/TS)
// Number with commas
function numberWithCommas(x: number): string {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function toLocaleStringSupportsLocales(number: number | string) {
if (typeof number === "string") {
return parseFloat(number).toLocaleString();
}
return number.toLocaleString();
}
console.log(numberWithCommas(123456789));
console.log(numberWithCommas(123_456_789));
console.log(numberWithCommas(123_456_789.0234242));
console.log(numberWithCommas(0.123456789));
console.log(toLocaleStringSupportsLocales(0));
console.log(toLocaleStringSupportsLocales(0.0000001));
console.log(toLocaleStringSupportsLocales("000"));
console.log(toLocaleStringSupportsLocales(123456_789));
console.log(toLocaleStringSupportsLocales(123456_789.123123123123));
console.log(toLocaleStringSupportsLocales(1_2345.678_9));
console.log(toLocaleStringSupportsLocales("1,234.56789"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment