//js方法格式化数字,加入千分符,并可以指定小数点位数 此乃 更为 严谨的 千分符
formatMoney(s, n) {
n = n >= 0 && n <= 20 ? n : 2;
s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
var l = s
.split(".")[0]
.split("")
.reverse(),
r = s.split(".")[1];
r = r == null ? "" : "." + r;
var t = "";
// console.log(l)
if (l[l.length - 1] === '-') {//负数不需要分隔号,
for (var i = 0; i < l.length; i++) {
if (l[i]==='-') {
t += l[i]+""
continue
}
//不是数组的倒数第二个元素才加"," ["0", "4", "5", "-"]
t += l[i] + ((i + 1) % 3 == 0 && i + 1 != l.length-1 ? "," : "");
//i + 1 != l.length会变成-,540.00,因为在5时元素位置2+1为3非数组长度
//t += l[i] + ((i + 1) % 3 == 0 && i + 1 != l.length ? "," : "");
}
}
else {
for (var i = 0; i < l.length; i++) {
t += l[i] + ((i + 1) % 3 == 0 && i + 1 != l.length ? "," : "");
}
}
return (
t.split("").reverse().join("") + r
);
},
原文链接: https://blog.csdn.net/hardly555/article/details/80162116