我正在尝试创建一个函数,它可以将数字格式化为最少2位小数和最多4位小数。因此,如果我传入354545.33,我将得到354,545.33,如果我传入54433.6559943,我将得到54,433.6559。
function numberFormat(num){
num = num+"";
if (num.length > 0){
num = num.toString().replace(/\$|\,/g,'');
num = Math.floor(num * 10000) / 10000;
num += '';
x = num.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
else{
return num;
}
}