当前位置: 首页 > 图文教程 > 网络编程 > Javascript > javascript之对系统的toFixed()方法的修正

Javascript
Add a Table to a Word Document
Add Formatted Text to a Word Document
用jscript实现新建word文档
用jscript实现新建和保存一个word文档
Open and Print a Word Document
Use Word to Search for Files
Convert Seconds To Hours
Sample script that deletes a SQL Server database
Sample script that displays all of the users in a given SQL Server DB
firefox中用javascript实现鼠标位置的定位
div+css实现鼠标放上去,背景跟图片都会变化。
Locate a File Using a File Open Dialog Box
Save a File Using a File Save Dialog Box
用jscript实现列出安装的软件列表
List the Stored Procedures in a SQL Server database
Display SQL Server Login Mode
Display SQL Server Version Information
List all the Databases on a SQL Server
用jscript启动sqlserver
Stop SQL Server

Javascript 中的 javascript之对系统的toFixed()方法的修正


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 73 ::
收藏到网摘: n/a

0.009.toFixed(2)本该返回0.01的结果,可它却返回了一个0.00,这是这个方法的一个BUG,且这个方法对客户端的JS版本要求有点偏高,至少在IE5.0里这个方法用不起来,所以我写了上面的一段修正代码,并且还解决了这个BUG的问题。若是想完全使用这个自定义的方法替代那个有BUG的系统方法的话,只需要去掉最外层的那个 if 判断就可以了。
//by meizz
if(typeof(Number.prototype.toFixed)!="function")
{
Number.prototype.toFixed=function (d)
{
var s=this+"";
if(!d)d=0;
if(s.indexOf(".")==-1)s+=".";
s+=new Array(d+1).join("0");
if(new RegExp("^(-|\\+)?(\\d+(\\.\\d{0,"+(d+1)+"})?)\\d*$").test(s))
{
var s="0"+RegExp.$2,pm=RegExp.$1,a=RegExp.$3.length,b=true;
if(a==d+2){
a=s.match(/\d/g);
if(parseInt(a[a.length-1])>4)
{
for(var i=a.length-2;i>=0;i--){
a[i]=parseInt(a[i])+1;
if(a[i]==10){
a[i]=0;
b=i!=1;
}else break;
}
}
s=a.join("").replace(new RegExp("(\\d+)(\\d{"+d+"})\\d$"),"$1.$2");
}if(b)s=s.substr(1);
return (pm+s).replace(/\.$/,"");
}return this+"";
};
}