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

Dart中NumberFormat如何设置舍入或截断模式?

如何控制NumberFormat采用截断(Floor)模式而非默认四舍五入

Dart的intl包中NumberFormat默认使用四舍五入模式,但并没有直接的shouldFloor属性,不过可以通过以下两种方式实现截断需求:

方法一:利用DecimalFormat的roundingMode属性

NumberFormat是DecimalFormat的抽象子类,我们可以将NumberFormat实例转为DecimalFormat,然后设置roundingMode为RoundingMode.floor来实现截断:

示例代码

import 'package:intl/intl.dart';
import 'package:intl/decimal_format.dart';

void example1() {
  // 创建NumberFormat实例并转为DecimalFormat
  final numberFormat = NumberFormat.currency(locale: 'en_US', symbol: '') as DecimalFormat;

  numberFormat.minimumFractionDigits = 2; // 最小小数位数
  numberFormat.maximumFractionDigits = 8; // 最大小数位数
  // 设置为截断模式
  numberFormat.roundingMode = RoundingMode.floor;

  print(numberFormat.format(1)); // 输出1.00
  print(numberFormat.format(321.00000000000)); // 输出321.00
  print(numberFormat.format(321.12345678)); // 输出321.12345678
  print(numberFormat.format(321.12345678901)); // 输出321.12345678
}

你也可以直接使用DecimalFormat创建实例,效果一致:

void example2() {
  final decimalFormat = DecimalFormat.currency(locale: 'en_US', symbol: '');
  decimalFormat.minimumFractionDigits = 2;
  decimalFormat.maximumFractionDigits = 8;
  decimalFormat.roundingMode = RoundingMode.floor;

  print(decimalFormat.format(321.12345678901)); // 输出321.12345678
}

方法二:手动截断数值后再格式化

如果不想依赖DecimalFormat的转换,也可以手动对数值进行截断处理,再传入NumberFormat格式化:

示例代码

import 'package:intl/intl.dart';
import 'dart:math';

// 自定义截断函数,保留指定小数位数
double truncateToDecimals(double num, int decimals) {
  final factor = pow(10, decimals);
  return (num * factor).floor() / factor;
}

void example3() {
  final numberFormat = NumberFormat.currency(locale: 'en_US', symbol: '');
  numberFormat.minimumFractionDigits = 2;
  numberFormat.maximumFractionDigits = 8;

  print(numberFormat.format(truncateToDecimals(321.12345678901, 8))); // 输出321.12345678
}

注意事项

  • 确保你的intl包版本支持roundingMode属性(建议使用最新稳定版);
  • 手动截断时需要注意浮点数精度问题,对于高精度数值场景,建议使用decimal包辅助处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 00:07:36