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

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 77 ::
收藏到网摘: 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+"";
};
}