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

Double转String时加减1.1出现精度异常问题求助

解决Double类型加减1.1的精度问题

这不是代码逻辑bug,是浮点数的二进制存储特性导致的精度丢失。像1.1这类十进制小数无法被二进制浮点数精确表示,多次运算后误差会累积,最终出现类似3.30000000003的异常结果。

以下是三种可行的解决方法:

1. 使用decimal库做精确小数运算

这是最稳妥的方案,专门用于处理需要精确精度的小数计算:

  • 先在pubspec.yaml中添加依赖:
    dependencies:
      decimal: ^2.3.3
    
  • 修改代码中的加减逻辑,用Decimal替代double:
    import 'package:decimal/decimal.dart';
    
    // 减法按钮逻辑
    setState(() {
      Decimal currentValue = Decimal.parse(value.isNotEmpty ? value : "0");
      Decimal result = currentValue - Decimal.parse("1.1");
      value = result.toString();
    });
    
    // 加法按钮逻辑
    setState(() {
      Decimal currentValue = Decimal.parse(value.isNotEmpty ? value : "0");
      Decimal result = currentValue + Decimal.parse("1.1");
      print(result);
      value = result.toString();
    });
    

2. 格式化输出结果,截断多余小数位

如果仅需要显示正常的数值,不需要极高精度,可以在转字符串时指定小数位数:

// 减法按钮修改
setState(() {
  value = (double.parse(value.isNotEmpty ? value : "0") - 1.1).toStringAsFixed(1);
});

// 加法按钮修改
setState(() {
  double newValue = double.parse(value.isNotEmpty ? value : "0") + 1.1;
  value = newValue.toStringAsFixed(1);
});

toStringAsFixed(1)会保留1位小数并自动四舍五入,完全匹配你每次加减1.1的操作场景。

3. 用整数模拟小数运算

将数值放大10倍转为整数,运算后再缩小10倍,彻底避开浮点数精度问题:

// 减法按钮逻辑
setState(() {
  int currentInt = int.parse(value.isNotEmpty ? (double.parse(value) * 10).toStringAsFixed(0) : "0");
  int resultInt = currentInt - 11; // 1.1 × 10 = 11
  value = (resultInt / 10).toString();
});

// 加法按钮逻辑
setState(() {
  int currentInt = int.parse(value.isNotEmpty ? (double.parse(value) * 10).toStringAsFixed(0) : "0");
  int resultInt = currentInt + 11;
  value = (resultInt / 10).toString();
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 15:53:17