0

I am getting unusual multiplication result in dart.

var val = 588.82;
  
print(val * 100); //result 58882.00000000001

What is the reason for this and how can I get the correct answer?

Dipak Pd.
  • 125
  • 2
  • 13
  • 2
    check this https://stackoverflow.com/questions/58834678/why-multiply-two-double-in-dart-result-in-very-strange-number – Diwyansh Jan 13 '22 at 08:57
  • 1
    are you trying to use that code for some currency operations? – pskink Jan 13 '22 at 08:59
  • @pskink yes, I'm using for razorpay – Dipak Pd. Jan 13 '22 at 09:00
  • 1
    see [Why not use Double or Float to represent currency?](https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency) - in short, the [accepted answer](https://stackoverflow.com/a/3730040/2252830) says: *"A solution that works in just about any language is to use integers instead, and count cents. For instance, 1025 would be $10.25"* – pskink Jan 13 '22 at 09:09

2 Answers2

1

This "problem" come with the IEEE 754 Standard, the floating point.

In short, many fractional double values are not precise.

588.82 is not really 588.82, if you want the correct value, you should probably round the result of the multiplication with two decimal.

maje
  • 424
  • 3
  • 17
-2
void main() {
  var val = 588.82;

  print((val * 100).toInt());
}
Yunus Kocatas
  • 286
  • 2
  • 9
  • 1
    I doubt this is going to be a useful answer. Presumably, in a real world application, they're not just multiplying by 100, and may not want to convert to an integer. They're trying to understand _why_ this happens, which the other answer helps address. – Jeremy Caney Jan 13 '22 at 18:15
  • absolutely you are right – Yunus Kocatas Jan 13 '22 at 19:17