0

Why is the answer weird when adding floating point numbers in JavaScript?

Can anyone explain why the answer for this code is: 0.30000000000000004 ??? var num2 = 0.1, num3 = 0.2, num4 = 0.3; document.write(num2 + num3);

3rd Apr 2018, 6:58 AM
tazzy
tazzy - avatar
6 Respostas
+ 2
In short, the same reason why some (particularly old) calculators give 9.9999 when you do 10 ÷ 3 and then × 3. For best precision these numbers require infinite decimal places but computers have finite memory (and floating point numbers have a set amount given to them) so you're going to come up against rounding errors etc. Floats are quick, and they're accurate 'enough' for many applications. Say you're using JS to position some elements on a screen - a user isn't going to notice that 0.0000004 discrepancy and the calculation will be much more performant than a data type that tries to avoid floating point errors. Floats are no good for financial applications though where precision matters
3rd Apr 2018, 7:12 AM
Dan Walker
Dan Walker - avatar
+ 2
Because in binary, 1/10, 3/10 is not terminating so has an infinite numbers of digits to the right, so any fraction whose denominator is not a power of 2 has this issue (like in base 10, any fraction whose denominator isn't exclusively powers of 2 and 5 has a repeating decimal)
3rd Apr 2018, 11:13 AM
Dan Walker
Dan Walker - avatar
+ 1
float numbers can't be calculated as decimal number, but as binary. Also the accuracy of this number is limited so sometimes it seems as it wouldn't calculate correctly
3rd Apr 2018, 7:01 AM
Aaron Eberhardt
Aaron Eberhardt - avatar
3rd Apr 2018, 7:04 AM
Aaron Eberhardt
Aaron Eberhardt - avatar
0
Thank you @Dan Walker. I can understand your explanation about the finite memory of a machine. But what I don’t understand is I’m giving the machine/calculator two finite numbers. Why isn’t it being calculated to 0.3 exactly?
3rd Apr 2018, 7:18 AM
tazzy
tazzy - avatar
0
Thank you, I’m still wrapping my head around this.
5th Apr 2018, 7:34 PM
tazzy
tazzy - avatar