为了更好的页面效果,我们往往不是将获取的数值直接显示。项目中有的时候根据需求,要将金额转换成“,”隔开显示。如1997 => 1,997
本次分享一个转换的方法:
html:
<div>
<p>1997</p>
<div>
js:
function formatCurrencyTenThou(num) {
num = num.toString().replace(/$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*10+0.50000000001);
//cents = num%10;
num = Math.floor(num/10).toString();
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+
num.substring(num.length-(4*i+3));
return (((sign)?'':'-') + num );
}
使用:
var num = $("p").text();
$("p").html(formatCurrencyTenThou(num));
效果:
(ps:是早前摘用别人封装的方法,出处非本人)