js toFixed()方法的重写实现精度的统一_javascript技巧

WBOY
Release: 2016-05-16 16:56:44
Original
2810 people have browsed it

但凡用过js 中的toFix() 方法的, 应该都知道这个方法存在一个小小的BUG。
在IE 下和FF 下对于小数的进位有点不同。
例如( 0.005)在ie 下 toFix(2)=0.00. 在FF 下 toFix(2)=0.01.
这样就会造成数据的差异。
我们可以通过 重写 这个方法来实现精度的统一。

复制代码代码如下:

Number.prototype.toFixed = function(s)
{
return (parseInt(this * Math.pow( 10, s ) + 0.5)/ Math.pow( 10, s )).toString();
}

但是这样做仍然有一个问题, 在所有的浏览器下, String("0.050").toFix(2)=0.1
我们可以看到这样你原本要保留两位小数却变成了一位。 也就是说。这个重写只有的toFixed() 会自动舍弃最后的0.
我们需要对这个方法做进一步的处理。
复制代码代码如下:

Number.prototype.toFixed = function(s)
{
changenum=(parseInt(this * Math.pow( 10, s ) + 0.5)/ Math.pow( 10, s )).toString();
index=changenum.indexOf(".");
if(index0){
changenum=changenum+".";
for(i=0;i changenum=changenum+"0";
}

}else {
index=changenum.length-index;
for(i=0;ichangenum=changenum+"0";
}

}

return changenum;
}
Related labels:
js
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!