+ 1
why output of this code is 0.30000000000000004 instead of 0.3
3 Answers
+ 3
This is a good question indeed.
The reason of the error is that computers store decimals in binary.
For example, 0.5 is 0.1(binary), just like 4 is 100(binary).
For 0.75, 0.25, 0.125, they can be saved as exact value.
For 0.3, it is saved as an approximation.
For more explicit explanation, I would recommend Anna's explanation to Kenny Wong.
https://www.sololearn.com/Discuss/1477626/?ref=app
Good job in thinking deep about these findings. You are on the right track. Keep up đȘ
0
js is not precise whan working with decimals and long numbers, you can use toFixed(1) to fix it to one decimal
console.log((0.1+0.2).toFixed(1))
for 2 decimal like 0.30 use toFixed(2) and so on..
I wraped it in () to group them and apply toFixed to sum of two decimal numbers.
0
I want to know how it calculate that answer will be equal to 0.30000000000000004 not for example 0.30000000000000013.
it's not just for JS.
in Python this problem also exists:
https://code.sololearn.com/cH3DIz79mKe7