0

I found this very simple calculation results incorrect: 0.19999999999999998. (This is happened on Dartpad too)

void main() {
    print(-0.1 + 0.3);
}

Why this is happened, and how to avoid ?

2 Answers2

1

That's because you are loosing precision when using the type double.

To avoid that you have a few alternatives:

  1. Use some decimal library like https://pub.dev/packages/decimal
  2. Multiply by the number of significant digits and do the math using integers, some more information on a related SO question Dart double division precision
Ariel Moraes
  • 602
  • 7
  • 15
0

This is due to the internal representation of floating point numbers that crops up in almost all programming languages; c.f. this tutorial on floating point representation.

What's going on under the hood is that the string "-0.1" is converted into a string of bits that correspond to a particular number that is approximately equal to the value $-0.1$; same for $0.3$. When you subtract them, these approximation errors line up in such a way as to produce a result that you get by doing the math symbolically.

If you really need "exact" math on numbers like this, you can look into packages that provide either a Decimal or a Rational type.

Dave
  • 7,555
  • 8
  • 46
  • 88