0.0000000001 difference in returned value (JAVASCRIPT SYNTAX, PART I, Sleep Debt Calculator)

link to exercise

Hello! I’m new to JavaScript and as I was working through the exercise Sleep Debt Calculator I noticed something weird:
there is a 0.0000000001 difference in some returned value… e.g. 1.1 + 2 returned 3.0999999999999 instead of 3.1.

This only happens to certain numbers, e.g.:
2.1 + 2 = 4.1
2.2 + 2 = 4.1999999999999999
2.3 + 2 = 4.3

In this case only 2.2 has this problem. Does anyone know what is the reason behind this? Is there possibly a fault in my code that caused this?

Thank you in advance! :pray:

Hello @0.110010, welcome to the forums! This problem is caused by float rounding errors. Essentially, because computers work in binary, they sometimes struggle to represent decimal numbers in base 10, and sometimes therefore create a value that’s off by a tiny amount. I would highly suggest reading the article I linked to for further information.

1 Like

hi @codeneutrino, thanks a lot! very interesting…

so in order to fix this problem (if really necessary), what would the best solution be?

e.g. in this case we want the value to have one decimal place. I found the method .toPrecision() and .toFixed() but none of them seems to solve the problem… e.g.: for the value of 0.1, when I use:-

a) getActualSleepHours.toFixed(0) returns 0, getActualSleepHours.toFixed(1) returns 0.10000000000000142
b) getActualSleepHours.toPrecision(2) returns 0, getActualSleepHours.toPrecision(3) returns 0.10000000000000142

🤷

One (pretty long-winded) solution is to turn the float into a string, then slice the string, getting rid of the unnecessary digits. But then you have to check whether the number is over or under, and round accordingly.


You could also try Math.round().

@codeneutrino I’ll experiment with it. Thanks a lot!

1 Like