0

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

enter image description here

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 4
    That's a common error with floating numbers. https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – Rémi Rousselet Oct 02 '18 at 06:12
  • 1
    In Java and Kotlin it's better to use BigDecimal instead of double. In dart you can try this https://pub.dartlang.org/packages/decimal (I didn't use this lib, so can't say how good it is) – Andrii Turkovskyi Oct 02 '18 at 06:41

1 Answers1

3

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).

lrn
  • 64,680
  • 7
  • 105
  • 121