var a = "-123456789.078";
a = (Math.round(a * 100) / 100).toFixed(2).toString().replace(/(\d)(?=(\d{3})+\.)/g, function($0, $1) {return $1 + ",";});
console.log(a)
可以将方法写成function,也可以自己在VUE或者angular绑定数据的时候直接使用。
如果需要保留任意一位小数可以将100写成变量
function formatNumber(a,n){
if(n===0){
a=a.replace(/(\d)(?=(\d{3})+$)/g,"$1,");
}else{
n1=Math.pow(10,n);
a = (Math.round(a * n1) / n1).toFixed(n).toString().replace(/(\d)(?=(\d{3})+\.)/g, function($0, $1) {return $1 + ",";});
}
return a;
}
var num1=formatNumber("-123456789.078771",4);
或者方法
function toThousands(num,n, separator) {
var parts;
num = num + "";
// 判断是否为数字
if (!isNaN(parseFloat(num)) && isFinite(num)) {
n1=Math.pow(10,n);
num = (Math.round(num* n1) / n1).toFixed(n);
parts = num.split(‘.‘);
parts[0] = parts[0].toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, ‘$1‘ + (separator || ‘,‘));
return parts.join(‘.‘);
}
return NaN;
}
var num1=toThousands("-123456789.078771",4);
原文地址:https://www.cnblogs.com/qiangonline/p/10141986.html