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
Share:
1,752
user1996206
Author by

user1996206

Updated on December 09, 2022

Comments

  • user1996206
    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?