when i run this code
_selectedCartList.forEach((group) {
group.cartModel.where((cartModel) => !cartModel.isSelected).forEach((cart) {
print('taxx $_tax - ${cart.tax} * ${cart.quantity}');
_tax -= cart.tax * cart.quantity;
});
});
this is what I got in the log
I/flutter ( 2664): taxx 243863.4 - 7562.5 * 1
I/flutter ( 2664): taxx 236300.9 - 119669.0 * 1
I/flutter ( 2664): taxx 116631.9 - 114829.0 * 1
I/flutter ( 2664): taxx 1802.8999999999942 - 1802.9 * 1
the taxx 243863.4 is the initial value. and in this part when things go wrong:
I/flutter ( 2664): taxx 116631.9 - 114829.0 * 1
I/flutter ( 2664): taxx 1802.8999999999942 - 1802.9 * 1
when I subtract 116631.9 - 114829.0 it gives me 1802.8999999999942 which something that's not supposed to
ANSWER FOR FLUTTER
as Some programmer dude said in the comment the explanation for this behavior is this Is floating point math broken?.
as for the solution in the flutter itself, i use this
_selectedCartList.forEach((group) {
String _roundedTax;
group.cartModel.where((cartModel) => !cartModel.isSelected).forEach((cart) {
_roundedTax = _tax.toStringAsFixed(1);
_tax = double.parse(_roundedTax);
print('taxx $_tax - ${cart.tax} * ${cart.quantity}');
_tax -= cart.tax * cart.quantity;
});
});
and the result is exactly how i want
I/flutter ( 2664): taxx 243863.4 - 7562.5 * 1
I/flutter ( 2664): taxx 236300.9 - 119669.0 * 1
I/flutter ( 2664): taxx 116631.9 - 114829.0 * 1
I/flutter ( 2664): taxx 1802.9 - 1802.9 * 1