is there a better way to multiply and divide figures than using the *
and /
?
There is a strange behavior in Chrome Firefox and Internet 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:
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With