0

I have the following code, which I expected tips is 0.00 at the end of the run. However it's 0.0.

print("cart['tips_percent']");
print(cart['tips_percent']);

print ("subTotal");
print (subTotal);

double tips = cart['tips_percent'] * subTotal;
tips = num.parse(tips.toStringAsFixed(2));
print(tips);

The log gives

I/flutter (31838): cart['tips_percent']
I/flutter (31838): 0.0
I/flutter (31838): subTotal
I/flutter (31838): 95.92
I/flutter (31838): 0.0
Christopher Moore
  • 15,626
  • 10
  • 42
  • 52
user1187968
  • 7,154
  • 16
  • 81
  • 152
  • Why do you expect 0.00 instead of 0.0? – Christopher Moore May 13 '20 at 22:54
  • because toStringAsFixed(2) – user1187968 May 13 '20 at 23:09
  • 1
    But you're parsing it back to a double and printing the result of that. `tips.toStringAsFixed(2)` probably has the correct value, but you parse it back to a double. – Christopher Moore May 13 '20 at 23:13
  • if You're going to print it why You parse it back from string? `double tips = cart['tips_percent'] * subTotal; print(tips.toStringAsFixed(2))` is enough – num8er May 13 '20 at 23:31
  • 1
    I feel obligated to mention that if you're storing currency, I would strongly discourage you from using `double`. You'd be much better off storing the number of cents (or whatever the smallest indivisible unit of currency is) as an `int` and then printing it in a friendlier format at the end. If you use `double`, you'll find that $0.10 + $0.10 + $0.10 is not $0.30 due to [floating point error](https://stackoverflow.com/questions/588004/is-floating-point-math-broken). – jamesdlin May 13 '20 at 23:59

1 Answers1

3

As mentioned by Christopher, you're parsing it back to a double, so it's never going to be 0.00. In this case, with the value as a double, the last digit is useless for any operation and it will only take more memory, so Dart doesn't store it.

To keep it, the only way will be as a String, so this will have to be your code:

double tips = cart['tips_percent'] * subTotal;
print(tips.toStringAsFixed(2));
Harry Knight
  • 256
  • 2
  • 5