ReactJs | Bad at math? Cant add 0.4 + 0.2 properly [duplicate]

Doing some calculations with react I noticed some weird stuff. Adding some numbers with decimals will result in weird numbers.

I created an entire new empty project and wrote just these 2 lines:

console.log(0.2 + 0.2);
console.log(0.4 + 0.2);

It should print you in console:

0.4
0.6

right? Well based on match - YES

BUT it prints out:

0.4
0.6000000000000001

For some reason, adding 0.4 and 0.2 together, adds and extra 0.0000000000000001 at the end?... WHY? How do I avoid it? It runs my calculations.

This happens with more numbers too.

Wrote a simple method to increment by decimals from 0 to 1

for (let i = 0; i < 1; i += 0.1) console.log(i);

With 0.1:

...
0.30000000000000004
...
0.7999999999999999
0.8999999999999999
0.9999999999999999

How does it go from 0.6 to 0.79 BY ADDING 0.1?!?

With 0.2:

...
0.6000000000000001
...

With 0.3:

...
0.8999999999999999

You get the idea. The [...] means before and/or after the numbers got added correctly, wish raises even a bigger question: how come adding 0.6000000000000001 + 0.2 u get 0.8???

Weirdly enough, with 0.25 everything is fine. even with 0.21!

tl;dr

ReactJs cant add single decimal numbers together properly. Any fixes?



Read more here: https://stackoverflow.com/questions/64398283/reactjs-bad-at-math-cant-add-0-4-0-2-properly

Content Attribution

This content was originally published by Lith at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: