需求:当金额大于10000时,在作展示的时候,需要加千分位逗号,就是每隔1000要用逗号分隔;
方法一:使用toLocaleString()方法
<script type= "text/javascript">
var num = "12356.546";
console.log(parseFloat(num).toLocaleString()); // 12,356
</script>
方法二
第二个方法性能更高,速度相对第一种方法快了将近9倍
<script>
'use strict'
let format = n => {
let num = n.toString()
let decimals = ''
// 判断是否有小数
num.indexOf('.') > -1 ? decimals = num.split('.')[1] : decimals
let len = num.length
if (len <= 3) {
return num
} else {
let temp = ''
let remainder = len % 3
decimals ? temp = '.' + decimals : temp
if (remainder > 0) { // 不是3的整数倍
return num.slice(0, remainder) + ',' + num.slice(remainder, len).match(/\d{3}/g).join(',') + temp
} else { // 是3的整数倍
return num.slice(0, len).match(/\d{3}/g).join(',') + temp
}
}
}
format(12323.33) // '12,323.33'
</script>
如果大家还有什么更高的解决方案,也可以在下面添加评论告诉我哦