You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中Double类型减法出现多位小数问题及解决方法

Flutter浮点运算精度异常问题及修复

问题现象

运行以下Flutter代码时:

_selectedCartList.forEach((group) {
    group.cartModel.where((cartModel) => !cartModel.isSelected).forEach((cart) {
      print('taxx $_tax - ${cart.tax} * ${cart.quantity}');
      _tax -= cart.tax * cart.quantity;
    });
  });

日志输出出现精度异常:

I/flutter ( 2664): taxx 243863.4 - 7562.5 * 1
I/flutter ( 2664): taxx 236300.9 - 119669.0 * 1
I/flutter ( 2664): taxx 116631.9 - 114829.0 * 1
I/flutter ( 2664): taxx 1802.8999999999942 - 1802.9 * 1

初始值为243863.4的_tax变量,在执行116631.9 - 114829.0运算后,得到了不符合预期的1802.8999999999942(预期应为1802.9)。

问题原因

这是典型的浮点数精度问题:二进制浮点数无法精确表示所有十进制小数,多次运算后微小的误差会逐渐累积,最终导致结果偏离预期。这类问题是浮点数运算的固有特性,属于业界普遍讨论的经典问题。

修复方案

通过每次运算前将_tax四舍五入保留1位小数,消除累积的精度误差,修复后的代码如下:

_selectedCartList.forEach((group) {
    String _roundedTax;
    group.cartModel.where((cartModel) => !cartModel.isSelected).forEach((cart) {
      _roundedTax = _tax.toStringAsFixed(1);
      _tax = double.parse(_roundedTax);
      print('taxx $_tax - ${cart.tax} * ${cart.quantity}');         
      _tax -= cart.tax * cart.quantity;
    });
  });

修复效果

修复后日志输出符合预期:

I/flutter ( 2664): taxx 243863.4 - 7562.5 * 1
I/flutter ( 2664): taxx 236300.9 - 119669.0 * 1
I/flutter ( 2664): taxx 116631.9 - 114829.0 * 1
I/flutter ( 2664): taxx 1802.9 - 1802.9 * 1

内容的提问来源于stack exchange,提问作者geezcake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 00:25:26