0
In the example below add up 0.3
plus 0.3
he will return me obviously 0.6
:
console.log(0.3 + 0.3);
But when trying to sum up 0.2
plus 0.1
it does not return me the result as 0.3
and yes a huge number as 0.30000000000000004
:
console.log(0.2 + 0.1)
I have found a solution which is to do the following operation:
console.log((0.2 * 10 + 0.1 * 10) / 10);
But I don’t understand why Javascript return me a huge number?
Possible duplicate of: Inaccurate result in broken numbers calculation
– Luiz Felipe
It’s not a huge number, it’s an unfurnished number. Internally the floating point numbers are represented in binary with a fixed number of digits. Neither 0.2 nor 0.1 has an exact floating-point binary value, so they are stored with a small error. When you add up, the sum of the errors becomes large enough to appear in the decimal printing. If you want to make sure that doesn’t happen, you have to work with whole numbers, or force a rounding type (0.1 + 0.2). toFixed(2)
– epx