2013-09-25 46 views
2

我想實現toFixed()以可靠的方式舍入到小數位(當前toFixed()函數在不同的瀏覽器中返回不同的結果)。實現toFixed()的最可靠方法是什麼?

我的想法是與Number.prototype.toFixed = function(c){};

我已經嘗試了多種選擇實現它,只有一個似乎很好地工作,但我不相信這件事:

乘以/ 10分多次分割和舍入((0.069).toFixed(2);返回「0.06999999999999999」):

Number.prototype.toFixed = function(c){ 
    var c = isNaN(c = Math.abs(c)) ? 0 : c; 
    var n = this; 
    for(var i=0; i<c; i++){ 
     n *= 10; 
    } 
    n = Math.round(n); 
    for(var i=0; i<c; i++){ 
     n /= 10; 
    } 
    n = (n+"").split("."); 
    if(c==0){ 
     return n[0]; 
    } 
    if(n[1] == void 0){ 
     n[1] = ""; 
    } 
    while(n[1].length<c){ 
     n[1]+="0"; 
    } 
    return n[0]+"."+n[1]; 
}; 

通過管理號碼作爲字符串(我仍然有這樣一個錯誤,例如:(0.0999).toFixed(2)給我「1.10」)

Number.prototype.toFixed = function(c){ 
    var c = isNaN(c = Math.abs(c)) ? 0 : c; 
     var d = (this+"").split("."); 
     if(d[1] == void 0){ 
      d[1] = ""; 
     } 
     if(d[1].length>c){ 
      if(parseInt(d[1].charAt(c))>=5){ 
       var cont = 0; 
       while(cont<c-1&&d[1].charAt(cont)==='0'){ 
        cont++; 
       } 
       var temp=""; 
       while(cont--){ 
        temp += "0"; 
       } 
       d[1]=temp+(parseInt(d[1].substring(0,c))+1)+""; 
       if(d[1].length>c){ 
        d[0]=(parseInt(d[0])+1)+""; 
        d[1]=d[1].substring(1); 
       } 
      } else { 
       d[1] = d[1].substring(0,c); 
      } 
     } 
     if(c==0){ 
      return d[0]; 
     } 
     while(d[1].length<c){ 
      d[1]+="0"; 
     } 
     return d[0]+"."+d[1]; 
}; 

乘以/ 10^C劃分和四捨五入我還沒有看到任何問題,但我不是太有信心:

Number.prototype.toFixed = function(c){ 
    var c = isNaN(c = Math.abs(c)) ? 0 : c; 
    var n = this; 
    var z = "1"; 
    for(var i=0; i<c; i++){ 
     z+="0"; 
    } 
    n = Math.round(n*z); 
    n /= z; 
    n = (n+"").split("."); 
    if(c==0){ 
     return n[0]; 
    } 
    if(n[1] == void 0){ 
     n[1] = ""; 
    } 
    while(n[1].length<c){ 
     n[1]+="0"; 
    } 
    return n[0]+"."+n[1]; 
}; 

我最好的選擇將是字符串操作之一,因爲你不要混淆浮動的不確定性,雖然它比我想象的更難以調試,並且我開始相信我永遠不會完美。除了這些之外,其他人是否已經實現了一個?

回答

1

這裏是我使用的代碼:

function RoundNumber(input, numberDecimals) 
{ 
    numberDecimals = +numberDecimals || 0; // +var magic! 

    var multiplyer = Math.pow(10.0, numberDecimals); 

    return Math.round(input * multiplyer)/multiplyer; 
} 

例子:

console.log(RoundNumber(1234.6789, 0)); // prints 1234 
console.log(RoundNumber(1234.6789, 1)); // prints 1234.6 
console.log(RoundNumber(1234.6789, 2)); // prints 1234.67 
console.log(RoundNumber(1234.6789, -1)); // prints 1230 

我已經在Chrome和Firefox瀏覽器中使用它。

相關問題