0

Dart calculations are off. We're running into rounding issues (financial app)

Here an example

Dartpad output

Hours              : 7.5
Rate               : 19.61
Val (Hours * Rate) : 147.075

Val * 100 (should be 14707.5) : 14707.499999999998
Round Val (now rounds down)   : 14707
Val / 100                     : 147.07 (should have been 147.08)

This is causing rounding errors displaying values to 2 decimal places.

Is there a way to accomplish this accurately in dart?

cjmarques
  • 632
  • 1
  • 7
  • 17
  • Regarding what to do in Dart: if you care about *decimal* precision, then you can use [`package:decimal`](https://pub.dev/packages/decimal). – jamesdlin Feb 23 '22 at 20:50

1 Answers1

0

This is a floating point precision thing, nothing really to do with the language itself. There are many ways around this problem. See mine below.

void main() {
  var vHours = 7.5;
  print('Hours              : $vHours');
  
  var vRate = 19.61;
  print('Rate               : $vRate');

  var vValue = vHours * vRate;
  print('Val (Hours * Rate) : $vValue');

  print('');
  var vMul = (vValue * 100);
  var vMulString = vMul.toStringAsFixed(2);
  var vMulParsed = num.parse(vMulString);
  print('Val * 100 (should be 14707.5) : $vMulParsed');
  var vMulRounded = vMulParsed.round();
  print('Round Val (now rounds down)   : $vMulRounded');
  
  var vDiv = vMulRounded / 100;
  print('Val / 100                     : $vDiv (should have been 147.08)');
}
Aidan Donnelly
  • 369
  • 5
  • 19