今天有朋友写代码的时候遇到了一个toFixed的问题,其实这个是一个很老的问题了。
简单记录一下,方便大家以后查看吧。
当然先介绍一下toFixed()这个api吧。
定义和用法
toFixed()方法可把Number四舍五入为指定小数位数的数字。
/* 参数num 必需,规定小数的位置 0~20之间,包括0和20 如果省略,就是0 */ NumberObject.toFixed(num);
问题还原:
var num = 0.009; alert(num.toFixed(2));
IE测试下会发现弹出的是0.00
当然有的同学到这里就觉得结束了,恩,我知道了一个原生api的bug
呵呵 坚持一下,下面给你解决一下这个问题
/* 改prototype.toFixed吧 虽然和buxiang这样做 遵循原生的返回的string */ Number.prototype.toFixed = function(n){ //Math.pow(10,n)-----10的n次方 //比如n是2,this是0.009 ----- //this * Math.pow( 10, s ) ------ 0.8999999999999999 //parseInt(this * Math.pow( 10, s ) + 0.5) -----1 //typeof (0.009.toFixed(2)) -----string return (parseInt(this*Math.pow(10,n)+0.5)/Math.pow(10,n)).toString() }