Because if you add 0.2 and 0.1 is returned a very large number?

Asked

Viewed 273 times

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?

  • 4
  • 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)

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.