Why is output of {42.05 + 0.05 } like this on Dart Lang?

307 Views Asked by At

When i try this on DartPad output is like this. Anyone can explain ?

enter image description here

1

There are 1 best solutions below

0
lrn On

This is expected behavior. Double numbers cannot represent all decimal fractions precisely, and neither 0.05 nor 42.05 are the exact values that the double values represent. The exact values are:

  • 42.0499999999999971578290569595992565155029296875
  • 0.05000000000000000277555756156289135105907917022705078125

If you add these two exact values, the result can yet again not be represented exactly as a double. The two closest representable doubles are:

  • 42.099999999999994315658113919198513031005859375
  • 42.10000000000000142108547152020037174224853515625

Of these, the former is closer to the correct result of the addition, so that is the double value chosen to represent that result.

This issue is not specific to Dart. All language using IEEE-754 64-bit floating point numbers will get the same result, and that is probably all languages with a 64-bit floating point type (C, C++, C#, Java, JavaScript, etc).