1

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?

user1996206
  • 98
  • 1
  • 10
  • 3
    Welcome to wonderful world of floating point numbers. Yes, that's normal and that question is asked often. See for example https://stackoverflow.com/questions/29197414/inexact-float-division and all the links in the comments there. – uaraven Mar 01 '19 at 03:21

4 Answers4

4

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

anmol.majhail
  • 48,256
  • 14
  • 136
  • 105
1

Using reduce will solve the problem

var total = [1.1, 2.2, 3.3].reduce((a, b) => a + b); // 6.6
Abdussalam
  • 19
  • 3
0

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.

João Cruz
  • 26
  • 3
0

For double type addition with round off



list.map<double>((m) => double.parse(m.totalTax.toDouble().toString())).reduce((a, b) => a + b).round()
poonam kalra
  • 135
  • 2
  • 8