例 sum=parseFloat(8.99)+parseFloat(7.50);
等到值为:16.4900000002
怎么只取到小数点后两位?
<script language="JScript">
Number.prototype.toFixed=function(num)
{
//重新构造toFixed方法,IE5.0+
with(Math)this.NO=round(this.valueOf()*pow(10,num))/pow(10,num);
return String(/\./g.exec(this.NO)?this.NO:this.NO+"."+String(Math.pow(10,num)).substr(1,num));
}
alert((12.9299).toFixed(2));
alert((12.9999).toFixed(2));
</script>
.toFixed(2)好象是不能四舍五入
等到值为:16.4900000002
怎么只取到小数点后两位?
<script language="JScript">
Number.prototype.toFixed=function(num)
{
//重新构造toFixed方法,IE5.0+
with(Math)this.NO=round(this.valueOf()*pow(10,num))/pow(10,num);
return String(/\./g.exec(this.NO)?this.NO:this.NO+"."+String(Math.pow(10,num)).substr(1,num));
}
alert((12.9299).toFixed(2));
alert((12.9999).toFixed(2));
</script>
.toFixed(2)好象是不能四舍五入
本文介绍了一种在JavaScript中实现数值保留到小数点后两位的方法,并通过自定义toFixed函数来确保数值的正确显示,适用于解决因浮点数运算导致的小数位数不准确问题。
1万+

被折叠的 条评论
为什么被折叠?



