Dart - Double datatype addition results in long decimal values
1,752
Solution 1
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
Solution 2
Using reduce will solve the problem
var total = [1.1, 2.2, 3.3].reduce((a, b) => a + b); // 6.6
Author by
user1996206
Updated on December 09, 2022Comments
-
user1996206 over 1 year
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?
-
uaraven about 5 yearsWelcome to wonderful world of floating point numbers. Yes, that's normal and that question is asked often. See for example stackoverflow.com/questions/29197414/inexact-float-division and all the links in the comments there.
-