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 ?
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 ?
That's because you are loosing precision when using the type double.
To avoid that you have a few alternatives:
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.