Javascript floating point calculation

I was wondering how I can subtract two negative floating point numbers in javascript. I tried:

alert(-0.2-0.1); 

and the result is -0.30000000000000004 . Am I doing something wrong? What do I need to do to get -0.3 ?

+8
javascript floating-point
source share
5 answers

No, there is nothing wrong with your code; most decimal fractions cannot be represented exactly in binary format.

 number.toFixed(x) 

Where x is the number of decimal places desired and number is the result of subtraction.

+13
source share

The reason for your problem is explained here: Why does the module operator return a fractional number in javascript?

A possible solution could be:

 <script type="text/javascript"> var result = (-20-10)/100; alert("My result is "+result); </script> 
+2
source share

toFixed() is what you should be looking for.

For example,

 number.toFixed(x); 

where x is the number of digits after the decimal point. It is optional with a default value of 0.

More details here: Javascript Number.toFixed () Method

+1
source share

You are not doing anything, what you see is a side effect of computers storing numbers in base 2. In base 10, 1/3 cannot be exactly represented: .33333333 (with a bar above 3). The same is true for 1/10 and 1/5 in base 2 or binary. The answer you see is simply the result of a rounding error. If you work with money, it is often recommended to store the values ​​as cents to avoid floating point errors.

As for fixing the result, you can do something like:

 var SIGDIG= 100000000; alert( Math.floor((-0.2-0.1)*SIGDIG)/SIGDIG ); 
+1
source share

Another possible solution might be the following:

 Number((-0.2-0.1).toFixed(x)) 

Where x should be the decimal point tolerance you would like.

Running this with x from 16 gives me -0.3 output.

 -0.3 === Number((-0.2-0.1).toFixed(16)) // true, and also with every 0 < x < 16 

Tell me.

0
source share

All Articles