一、添加千分位
转成千分位-保留两位小数-兼容负数版
export function thousands (n) {
const num = NToFixed(n, 2)
// 匹配前面是1到3个的数字后面跟着3个数字的
const re = /\d{1,3}(?=(\d{3})+$)/g
return `${num}`.replace(/^(\-?)(\d+)((\.\d+)?)$/, function (s, s1, s2, s3) {
return s1 + s2.replace(re, '$&,') + s3
})
}
转成千分位-保留两位小数-兼容负数版-精简
function thousands (num) {
return (+num || 0).toString().replace(/^-?\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, ','))
}
1.1 千分位效果与问题
效果
假如一个数为1000,那么千分为会改为1,000,
问题:可能在前端拿值会丢失,如下
解决措施接受把千分为去除,下面博主写一个通用的去除千分为方法
二、去除千分为位
function delcommafy(num){//去除千分位中的‘,’
if(num&&num!='undefined'&&num!='null'){
let numS = num;
numS = numS.toString();
numS = numS.replace(/,/gi, '');
return numS;
}else {
return num;
}
}
运用
结果