Created
March 19, 2022 14:10
-
-
Save alphaolomi/e79f2afbfd4ec494904a10d067a33006 to your computer and use it in GitHub Desktop.
Number with commas (JS/TS)
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
| // 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