2010-06-29 131 views
4

有沒有比使用*/乘法和除數更好的方法?Javascript計算錯誤

有在Chrome Firefox和Internet Explorer一個奇怪的行爲使用這些則算:

x1 = 9999.8 
x1 * 100 = 999979.9999999999 
x1 * 100/100 = 9999.8 
x1/100 = 99.99799999999999 

http://jsbin.com/ekoye3/

我想本輪下跌的用戶輸入與parseInt (x1 * 100)/100,結果爲9999.89999.79

我應該用另一種方式來達到這個目的嗎?

回答

7

這是沒有錯誤。你可能想看看:在浮點

整數運算是精確的,可以通過縮放來避免這樣的十進制表示的錯誤。例如:

x1 = 9999.8;       // Your example 
console.log(x1 * 100);     // 999979.9999999999 
console.log(x1 * 100/100);   // 9999.8 
console.log(x1/100);     // 99.99799999999999 

x1 = 9999800;       // Your example scaled by 1000 
console.log((x1 * 100)/10000);  // 999980 
console.log((x1 * 100/100)/10000); // 9999.8 
console.log((x1/100)/10000);  // 99.998 
+0

哇 - 非常感謝你 – jantimon 2010-06-29 08:21:37

+0

整數運算只是精確到一個點,甚至1 ULP!= 1 – 2010-06-29 10:41:29

1

你可以使用toFixed()方法:

var a = parseInt (x1 * 100)/100; 
var result = a.toFixed(1); 
+0

謝謝 - 不知道'.toFixed'它的效果很好。但是,你可能意思是'x1.toFixed(2)' - 不是嗎? – jantimon 2010-06-29 08:36:37