user1996206
user1996206

Reputation: 108

Dart - Double datatype addition results in long decimal values

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

Answers (4)

poonam kalra
poonam kalra

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

Jo&#227;o Cruz
Jo&#227;o Cruz

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

Abdussalam
Abdussalam

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

anmol.majhail
anmol.majhail

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

Related Questions