1.实现目标
需求描述:
我们有一串数字: 892345678.345672
, 需要把它格式化为892,345,678.345672
需求很简单, 我们来实现它吧
2.数组逆序法
代码实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| function format(num) { const str = num.toString().split('.'); const intNum = str[0]; const fraction = str[1]; const arr = intNum.split('').reverse(); let result = ''; arr.forEach((item, index) => { if(index !== 0 && index % 3 === 0) { result = `${item},${result}` } else { result = item + result; } }) return result + (fraction ? '.' + fraction : ''); }
|
使用
1 2 3 4 5 6 7 8
| format(892345678.345672) format(892345678) format(892)
输出: 892,345,678.345672 892,345,678 892
|
上段代码中我们有几点需要注意:
3.字符串分割法
相较于数组逆序法,字符串分割法性能要相较于而言高一点,因为数组操作特别是一些打乱顺序得到操作其实是比较消耗性能的。
在JS
中,字符串本身就是可以循环的,而且本道题目输出的也是字符串,所以我们可以直接操作字符串。
代码实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| function format(num) { const str = num.toString().split('.'); const intNum = str[0]; const fraction = str[1]; const length = intNum.length; let result = ''; for(let index = length -1; index >= 0; index--) { const i = length - index; if(i % 3 === 0) { if(index === 0) { result = intNum[i] + result } else { result = ',' + intNum[i] + result } } else { result = intNum[i] + result } } return result + (fraction ? '.' + fraction : ''); }
|
使用
1 2 3 4 5 6 7 8
| format(892345678.345672) format(892345678) format(892)
输出: 892,345,678.345672 892,345,678 892
|
上段代码中需要注意的点如下:
4.toLocaleString()
toLocaleString()
API
简单介绍用法:
Number.prototype.toLocaleString()
方法返回这个数字在特定语言环境下的字符串表示。
该方法拥有两个可选参数,分别是locales
和options
。locales
是缩写的语言代码或这些代码组成的数组,options
参数指定了一些附加的样式属性。
1、当忽略两个参数时,Number.prototype.toLocaleString()
方法返回当前系统使用的默认语言环境和默认选项格式化的字符串。
1 2 3
| var num = 12345; num.toLocaleString(); num.toString();
|
2、使用locales参数
1 2
| var num = 1234567890; num.toLocaleString('zh-Hans-CN-u-nu-hanidec');
|
3、使用options参数
1 2
| var num = 123456.789; num.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' });
|
如上, 我们采用第一种用法就可实现千分位, 代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13
| function format(num) { return num.toLocaleString(); }
用法: format(892345678.345672) format(892345678) format(892)
输出: 892,345,678.345672 892,345,678 892
|
5.使用正则
正则也是大家很容易想到的一种方式,不过正则的效率没有大家想象的那么好,当然如果在实际项目中,什么用起来简单用什么。
代码实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| function format(num){ const REG = /\B(?=(\d{3})+(?!\d))/g; return num.toString().replace(REG, ","); }
用法: format(892345678.345672) format(892345678) format(892)
输出: 892,345,678.345672 892,345,678 892
|
总结
想要实现该需求,方式多种多样,具体使用哪一种方式需要结合实际应用场景,比如说需要性能好一点,或者说需要代码简洁一点等等。出了上面几种,还有很多种方式可以实现,这就需要大家自己下去挖掘了。