Flutter项目开发中,对数据进行处理,需要四舍五入保留两位小数,正好有个数据是“9.87*3.5 = 34.545 ”用num.dart 的String toStringAsFixed(int fractionDigits)方法,但是结果却变成了34.54和Java的double计算丢经度是一个道理,具体原理可以看JAVA double精度丢失问题下面是工具类可以直接使用
import 'package:decimal/decimal.dart';
import 'package:intl/intl.dart';
/// Num Util.
class NumUtils {
/// 加 (精确相加,防止精度丢失).
static double add(num a, num b) {
Decimal d1 = Decimal.parse(a.toString());
Decimal d2 = Decimal.parse(b.toString());
return (d1 + d2).toDouble();
}
/// 加 (精确相加,防止精度丢失).四舍五入保留指定位数小数
static String addStr(num a, num b, int digits) {
Decimal d1 = Decimal.parse(a.toString());
Decimal d2 = Decimal.parse(b.toString());
return (d1 + d2).toDouble().toStringAsFixed(digits);
}
/// 减 (精确相减,防止精度丢失).
static double subtract(num a, num b) {
Decimal d1 = Decimal.parse(a.toString())

文章提供了一个名为NumUtils的工具类,用于在Flutter开发中进行精确的数值运算,避免浮点数精度丢失问题。类中包含加、减、乘、除等方法,并提供了四舍五入保留指定小数位的功能,确保了如9.87*3.5得到34.545这样的正确结果。
最低0.47元/天 解锁文章
2000

被折叠的 条评论
为什么被折叠?



