Reputation: 108
In the following program I am adding the list of doubles.
The output I am expecting is 57.7 but it results in 57.699999999999996
void main() {
List<double> list= [1.0,1.0,1.0,1.0,0.8,52.9];
double total = 0.0;
list.forEach((item) {
total = total + item;
});
print(total);
}
Is this a expected behaviour?
Upvotes: 2
Views: 3082
Reputation: 160
For double type addition with round off
list.map<double>((m) => double.parse(m.totalTax.toDouble().toString())).reduce((a, b) => a + b).round()
Upvotes: 0
Reputation: 26
This is due to floating point math. This behavior is common in many languages. If you want to know more about this I recommend this site. Some languages like Java have classes made to work with this type of precise operation, however Dart does not have official support for this, luckily to get around this problem there is a package one. I'll show you what worked for me here. Using your code would look like this:
First of all to solve the main problem we must use a package called decimal, add the following dependency in your pubspec.yaml and update the packages:
name: ...
dependencies:
decimal: ^0.3.5
...
Then your file will look like this:
import 'package:decimal/decimal.dart';
void main() {
List<double> list = [1.0, 1.0, 1.0, 1.0, 0.8, 52.9];
double total = list.fold(0, (total, value) {
var result = Decimal.parse(total.toString()) + Decimal.parse(value.toString());
return double.parse(result.toString());
});
print(total); // 57.7
}
Obs: I used the google translator.
Upvotes: 0
Reputation: 17
Using reduce will solve the problem
var total = [1.1, 2.2, 3.3].reduce((a, b) => a + b); // 6.6
Upvotes: 0
Reputation: 51306
Yes, that is expected behavior - to get the desired result use - .toStringAsFixed(1)
void main() {
List<double> list = [1.0, 1.0, 1.0, 1.0, 0.8, 52.9];
double total = 0.0;
list.forEach((item) {
total = total + item;
});
print(total.toStringAsFixed(1));
}
output: 57.7
Upvotes: 5