【问题标题】:How to round a double up to a given degree of precision after the decimal point?如何在小数点后将 double 舍入到给定的精度?
【发布时间】:2022-12-13 22:46:29
【问题描述】:
我需要始终将数字四舍五入,并保留给定的小数位数
例如
2000.301 -> 2000.31
2000.309 -> 2000.31
2000.999 -> 2001.00
2000.001 -> 2000.01
toStringAsFixed() // cant help with that
// need something like ceil(), but for decimal
【问题讨论】:
标签:
dart
double
decimal
rounding
【解决方案1】:
如果您在四舍五入前将 0.5 添加到一个数字中,它将始终向上四舍五入。
将其应用到小数点后两位,您将得到:
(2000.301 + 0.005).toStringAsFixed(2)
=> 2000.31
诀窍是在小数点和 5 之间添加尽可能多的 0s,因为你希望在输出中有有效的小数点。
将其转化为效用函数可能如下所示:
import 'dart:math';
String roundToDecimals(double value, int decimals) {
final corr = 0.5 * pow(0.1, decimals);
return (value + corr).toStringAsFixed(decimals);
}