Reputation: 39859
I just stumble accross something really odd in Javascript.
My script was multiplying 13596 by 0.1, and the output was : 1359.6000000000001
We can agree that 0.1 = 1/10, so I tried it :
13596/10 = 1359.6
I tested it with Firefox and Chrome, the same results occurs.
I wondered if it was related to floating, so I tried the following :
13596 * parseFloat(0.1) = 1359.6000000000001
Nope.
By the way, this is not equal :
(13596*0.1) === (13596/10) => false
Does anyone has an idea about this result ?
Upvotes: 3
Views: 118
Reputation: 310832
Remember that, with floating points, a number you see on-screen is not necessarily exactly the number the computer is modelling.
For example, using node
:
> 1359.6
1359.6
> (1359.6).toFixed(20)
'1359.59999999999990905053'
Node shows you 1359.6
, but when you ask for more precision, you can see that the real number is not exactly what you saw -- it was rounded. The same is true of 0.1:
> (0.1).toFixed(20)
'0.10000000000000000555'
Generally when you work with floats you accept this imprecision and round numbers before displaying them.
Some numbers are exactly representable, but it's safest to assume that floating point is imprecise. For example, 0.5 can be represented exactly:
> (0.5).toFixed(20)
'0.50000000000000000000'
Dividing by 10 actually produces the same result as multiplying by 0.1:
> 13596/10
1359.6
> (13596/10).toFixed(20)
'1359.59999999999990905053'
In other languages division between integers results in an integer, however in JavaScript all numbers are modelled as floating points.
Generally whenever you need to precisely represent decimal numbers you should use a decimal number type, though this is not available natively in JavaScript.
Also there is no point to use the code parseFloat(0.1)
as 0.1
is already a float.
Upvotes: 8