1

在下面的程序中,我添加了双打列表。

我期望的输出是 57.7,但结果是 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);

}

这是预期的行为吗?

4

4 回答 4

4

是的,这是预期的行为 - 获得预期的结果使用 -.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));
}

输出:57.7

于 2019-03-01T06:38:17.530 回答
1

使用reduce会解决问题

var total = [1.1, 2.2, 3.3].reduce((a, b) => a + b); // 6.6
于 2020-07-09T19:31:03.300 回答
0

这是由于浮点数学。这种行为在许多语言中很常见。如果你想知道更多关于这个我推荐这个网站。像 Java 这样的一些语言有类来处理这种类型的精确操作,但是 Dart 没有对此的官方支持,幸运的是,有一个包可以解决这个问题。我会告诉你什么对我有用。使用您的代码将如下所示:

首先要解决主要问题,我们必须使用一个名为 decimal 的包,在 pubspec.yaml 中添加以下依赖项并更新包:

name: ...
dependencies:
  decimal: ^0.3.5
  ...

然后您的文件将如下所示:

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:我使用了谷歌翻译。

于 2020-07-29T09:57:29.407 回答
0

用于带舍入的双类型加法



list.map<double>((m) => double.parse(m.totalTax.toDouble().toString())).reduce((a, b) => a + b).round()
于 2020-12-23T08:08:19.847 回答