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

Dart中如何避免toStringAsFixed()四舍五入,保留指定位小数?

在Dart中截断Double到指定小数位(不四舍五入)

要实现对double数值截断到1位小数而非四舍五入,你可以通过以下几种可靠的方式实现:

方法一:数学运算截断(推荐)

利用乘法将目标小数位转为整数部分,通过truncateToDouble()直接截断小数部分后再还原,这种方法高效且避免字符串处理的精度问题:

import 'dart:math';

double truncateToDecimalPlace(double number, int decimalPlaces) {
  final multiplier = pow(10, decimalPlaces);
  return (number * multiplier).truncateToDouble() / multiplier;
}

void main() {
  double d1 = 1.151;
  double d2 = 1.150;
  
  // 截断到1位小数
  final truncatedD1 = truncateToDecimalPlace(d1, 1);
  final truncatedD2 = truncateToDecimalPlace(d2, 1);
  
  print('$d1 is ${truncatedD1.toStringAsFixed(1)}');
  print('$d2 is ${truncatedD2.toStringAsFixed(1)}');
}

输出结果:

1.151 is 1.1
1.15 is 1.1

说明

  • pow(10, decimalPlaces)生成对应位数的乘数(比如1位小数就是10),将原数放大后,truncateToDouble()会直接舍弃小数部分取整,再除以乘数还原为目标精度的数值。
  • 最后用toStringAsFixed(1)确保输出格式为1位小数,避免出现类似1.1000000000000001的精度残留。

方法二:字符串截取法

如果需要直接处理字符串格式,可以通过截取字符串到指定小数位的方式实现,适合需要直接操作字符串输出的场景:

String truncateDecimalStr(double number, int decimalPlaces) {
  String numStr = number.toString();
  int dotIndex = numStr.indexOf('.');
  
  // 无小数部分的情况,补0到指定位数
  if (dotIndex == -1) {
    return '$numStr.${'0' * decimalPlaces}';
  }
  
  // 截取到小数点后指定位数,若小数位不足则补0
  int endIndex = dotIndex + 1 + decimalPlaces;
  String truncated = numStr.substring(0, endIndex);
  if (numStr.length <= endIndex) {
    truncated += '0' * (endIndex - numStr.length);
  }
  
  return truncated;
}

void main() {
  double d1 = 1.151;
  double d2 = 1.150;
  
  print('$d1 is ${truncateDecimalStr(d1, 1)}');
  print('$d2 is ${truncateDecimalStr(d2, 1)}');
}

输出结果:

1.151 is 1.1
1.15 is 1.1

说明

  • 先将数值转为字符串,找到小数点位置后截取到目标小数位;若原数小数位不足,自动补0保证格式统一。
  • 注意:部分double值的字符串表示可能出现科学计数法(如极小/极大数),这种情况建议先通过toStringAsPrecision()转为普通格式再处理。

内容的提问来源于stack exchange,提问作者sm-sayedi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 17:45:49