Javascript calculation bug
is there a better way to multiply and divide figures than using the *
and /
?
There is a strange behavior in Chrome Firefox and Inte开发者_StackOverflow社区rnet Explorer using those operaters:
x1 = 9999.8
x1 * 100 = 999979.9999999999
x1 * 100 / 100 = 9999.8
x1 / 100 = 99.99799999999999
http://jsbin.com/ekoye3/
I am trying to round down the user input with parseInt ( x1 * 100 ) / 100
and the result for 9999.8
is 9999.79
Should I use another way to achieve this?
That's no bug. You may want to check out:
- Is JavaScript’s math broken?
Integer arithmetic in floating-point is exact, so decimal representation errors can be avoided by scaling. For example:
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
You could use the toFixed() method:
var a = parseInt ( x1 * 100 ) / 100;
var result = a.toFixed( 1 );
You may want to check this. If you want to do computation on numbers which represent money, you should count cents and use integers.
精彩评论