views:

63

answers:

3

Hi,

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?

+1  A: 

You could use the toFixed() method:

var a = parseInt ( x1 * 100 ) / 100;
var result = a.toFixed( 1 );
Darin Dimitrov
Thanks - didn't know `.toFixed` it works great. However you probably meant `x1.toFixed( 2 )` instead - didn't you?
Ghommey
+4  A: 

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
Daniel Vassallo
wow - thank you so much
Ghommey
integer arithmetic is only exact up to a point, eventially 1 ULP != 1
jk
+1  A: 

You may want to check this. If you want to do computation on numbers which represent money, you should count cents and use integers.

Alexandre C.