在涉及到金额的情况下,一般来说,都需要用千分位的方式进行展示。更利于用户阅读。
接下来介绍两种常用的方案。
第一种:toLocaleString()
toLocaleString() 方法返回这个数字在特定语言环境下的表示字符串。具体用法可查看MDN介绍
第二种:使用正则表达式替换
function format(number) {
const num = String(number)
const reg = /\d{1,3}(?=(\d{3})+$)/g
const res = num.replace(/^(-?)(\d+)((\.\d+)?)$/, function(match, s1, s2, s3){
return s1 + s2.replace(reg, '$&,') + s3
})
return res
}
console.log(format(-123568.4758))
// 结果
-123,568.4758
补充一个toFixed的方法
function myToFixed(data, n) {
var result = parseFloat(data);
result = Math.round(data * Math.pow(10, n)) / Math.pow(10, n);
var s_x = result.toString();
var pos_decimal = s_x.indexOf('.');
if (pos_decimal < 0) {
pos_decimal = s_x.length;
s_x += '.';
}
while (s_x.length <= pos_decimal + n) {
s_x += '0';
}
return s_x;
}