我需要小数四舍五入到使用JavaScript六个地方,但我需要考虑传统的浏览器,所以我能“T依靠Number.toFixed

  

在大收获与toExponential,toFixed和toPrecision是它们在Mozilla不支持直到火狐版本1.5(虽然IE支持,因为版本5.5的方法)相当现代构建体。虽然它主要是安全使用这些方法,老的浏览器将打破,所以如果你正在写我们建议您提供自己的原型为旧版浏览器的为这些方法提供功能的公共项目。

我使用的是类似

考虑
Math.round(N*1000000)/1000000

什么是用于提供此原型以旧的浏览器的最佳方法?

有帮助吗?

解决方案

尝试这种情况:

if (!Number.prototype.toFixed)

    Number.prototype.toFixed = function(precision) {
        var power = Math.pow(10, precision || 0);
        return String(Math.round(this * power)/power);
    }

其他提示

我认为Firefox 1.5及IE 5是几乎不再使用,或由人一个很小的数量。结果 这是一个有点像编码支持的Netscape Navigator ... :-)结果 除非一些其他的主流浏览器(歌剧?Safari浏览器?不可能......)不支持这一点,或者如果您的Web日志显示大量的旧版浏览器,你可能只需要使用这些方法。结果 有时,我们必须继续前进。 ^ _ ^

[编辑]在Opera 9.50和Safari 3.1工程细

javascript: var num = 3.1415926535897932384; alert(num.toFixed(7));

您引用的文章是一年半以前,在IT行业一个永恒的......我想,不像IE用户,Firefox用户常去的最新版本。

字节网站,这个功能是几乎比塞尔llinsky的是相同的:

if (!num.toFixed) 
{
  Number.prototype.toFixed = function(precision) 
  {
     var num = (Math.round(this*Math.pow(10,precision))).toString();
     return num.substring(0,num.length-precision) + "." + 
            num.substring(num.length-precision, num.length);
  }
}

另一种选择是(其不转换为字符串不必要,并且还校正的(162.295).toFixed(2)162.29(应该是162.30)的计算错误)。结果

Number.prototype._toFixed=Number.prototype.toFixed; //Preserves the current function
Number.prototype.toFixed=function(precision){
/* step 1 */ var a=this, pre=Math.pow(10,precision||0);
/* step 2 */ a*=pre; //currently number is 162295.499999
/* step 3 */ a = a._toFixed(2); //sets 2 more digits of precision creating 16230.00
/* step 4 */ a = Math.round(a);
/* step 5 */ a/=pre;
/* step 6 */ return a._toFixed(precision);
}
/*This last step corrects the number of digits from 162.3 ( which is what we get in
step 5 to the corrected 162.30. Without it we would get 162.3 */

编辑:在尝试此特定化身,this*=Math.pow(10, precision||0)创建一个出错无效左手分配。所以给了这个关键字的变量a。这也将有助于如果我闭上了功能^ _ ^ ;;

尝试这种情况:

 Number.prototype.toFixed = function(precision) {
     var power = Math.pow(10, precision || 0);
     return String(Math.round(this * power)/power);
 }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top