What you are experiencing is the main floating point rounding error.
We cannot represent exactly 0.1 without some error due to the nature of binary numbers. WolframAlpha reports the decimal value of 0.1 into equal binary ~ 0.00011001100110011 ... Note how it cannot be finally represented in a binary number system? This means that we must decide on the cut-off point at which to stop calculating this number, otherwise we would be here forever.
This results in an error. And this error has accumulated as the code adds numbers together, which leads to an incredibly small amount added to the end of your amount. This ensures that the amount will never be EXACTLY 0.3 that the IF
test is looking for.
Some decimal numbers, however, can be represented exactly in binary form, such as dec 0.5 = bin 0.1 and dec 0.25 = bin 0.01.
We can demonstrate this in the same way as the original code, using 0.5 = (0.25 + 0.25).
For further reference, I recommend the Floating Point Guide .
It gives a good overview of the concept of floating point numbers and how computational errors can occur. There is also a section on Javascript that demonstrates how to overcome the rounding errors you experience.
source share