Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 575
jantimon Avatar asked Jan 21 '23 20:01

jantimon


2 Answers

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
like image 77
Daniel Vassallo Avatar answered Feb 03 '23 18:02

Daniel Vassallo


You could use the toFixed() method:

var a = parseInt ( x1 * 100 ) / 100;
var result = a.toFixed( 1 );
like image 45
Darin Dimitrov Avatar answered Feb 03 '23 18:02

Darin Dimitrov