2011-11-28 46 views
1

Number#toFixed()對於某些號碼無法正常工作。 如: -`toFixed()`對於某些號碼無法正常工作

7.795.toFixed(2) 
//-> 7.79     #Instead it should display 7.80 

8.895.toFixed(2) 
//-> 8.89     #Instead it should display 8.90 

1.105.toFixed(2) 
//-> 1.10     #Instead it should display 1.11 

55.305.toFixed(2) 
//-> 55.30     #Instead it should display 55.31 

請爲我提供了一個解決這個問題。

+1

'toFixed()'是Javascript方法 - 無關的jQuery – ManseUK

回答

1

這不是一個jQuery錯誤,這是默認Javascript的行爲。

的溶液可以是:

(Math.round(55.305 * 100)/100) = 55.31 
+0

**(Math.round( 9.995 * 100)/ 100)= 9.99#而應該顯示100 ** –

+0

如果你不想在逗號後面加任何數字。只需使用'Math.round(9.995)' – Niels

+0

我想要小數點後的兩個數字。 –

2
function round_float(x,n){ 
    if(!parseInt(n)) 
    var n=0; 
    if(!parseFloat(x)) 
    return false; 
    return Math.round(x*Math.pow(10,n))/Math.pow(10,n); 
} 
round_float(1.105,2).toFixed(2); 

//結果:1.11

相關問題