Dart - Subtracting some double values gives wrong result

Viewed 1611

I have picked two random double numbers:

double a = 7918.52;
double b = 5000.00;

I would expect to get 2918.52 from a - b.
Well, it gives me a result of 2918.5200000000004, which seems odd.

print(a - b); // -> 2918.5200000000004

But if I change double a to 7918.54, I will get the expected result of 2918.54.

Can someone explain to me why some double values result in unexpected rounding issues and others do not?

2 Answers

creativecreatorormaybenot is right, this is issue comes from the Dart language itself.

The best solution I came up with was to manually round it to the precision you expect :

double substract(double a, double b, int precision) {
  return (a - b).precision(precision);
}

double precision(int fractionDigits) {
  num mod = pow(10.0, fractionDigits);
  return ((this * mod).round().toDouble() / mod);
}
Related