核心提示:有时为了阅读方便,需要将大数值展示为逗号表示法。当然将数值转为数组在插入逗号方式可行。介绍两种简便方法:1. 使用toLocaleString()方法。 10154545450.42.toLocale...
有时为了阅读方便,需要将大数值展示为逗号表示法。
当然将数值转为数组在插入逗号方式可行。
介绍两种简便方法:
1. 使用toLocaleString()方法。
> 10154545450.42.toLocaleString('en-US') < "10,154,545,450.42" > (-1234567.8912).toLocaleString('en-US') < "-1,234,567.891"
使用正则替换,在SO上有高票答案:
const numberWithCommas = (x) => { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); }
测试:
> numberWithCommas(12345678.54321) < "12,345,678.54,321" > numberWithCommas(-12345678.54321) < "-12,345,678.54,321"