如何在小数点后将 Dart 中的双精度舍入到给定的精度? [英] How do you round a double in Dart to a given degree of precision AFTER the decimal point?
问题描述
给定一个double,我想把它四舍五入到给定的精度小数点后,类似于PHP的round()函数.
Given a double, I want to round it to a given number of points of precision after the decimal point, similar to PHP's round() function.
我能在 Dart 文档中找到的最接近的东西是 double.toStringAsPrecision(),但这并不是我所需要的,因为它在总精度点数中包含小数点之前的数字.
The closest thing I can find in the Dart docs is double.toStringAsPrecision(), but this is not quite what I need because it includes the digits before the decimal point in the total points of precision.
例如,使用 toStringAsPrecision(3):
For example, using toStringAsPrecision(3):
0.123456789 rounds to 0.123
9.123456789 rounds to 9.12
98.123456789 rounds to 98.1
987.123456789 rounds to 987
9876.123456789 rounds to 9.88e+3
随着数字的大小增加,我相应地失去小数点后的精度.
As the magnitude of the number increases, I correspondingly lose precision after the decimal place.
推荐答案
String toStringAsFixed(int fractionDigits)
String toStringAsFixed(int fractionDigits)
返回一个小数点字符串表示形式.
Returns a decimal-point string-representation of this.
在计算字符串表示之前将其转换为双精度值.
Converts this to a double before computing the string representation.
- 如果 this 的绝对值大于或等于 10^21,则此方法返回由 this.toStringAsExponential() 计算的指数表示.
- If the absolute value of this is greater or equal to 10^21 then this methods returns an exponential representation computed by this.toStringAsExponential().
示例:
1000000000000000000000.toStringAsExponential(3); // 1.000e+21
- 否则,结果是最接近的字符串表示形式,小数点后正好有fractionDigits 位.如果fractionDigits 等于0,则省略小数点.
参数fractionDigits 必须是满足以下条件的整数:0 <=fractionDigits <= 20.
The parameter fractionDigits must be an integer satisfying: 0 <= fractionDigits <= 20.
示例:
1.toStringAsFixed(3); // 1.000
(4321.12345678).toStringAsFixed(3); // 4321.123
(4321.12345678).toStringAsFixed(5); // 4321.12346
123456789012345678901.toStringAsFixed(3); // 123456789012345683968.000
1000000000000000000000.toStringAsFixed(3); // 1e+21
5.25.toStringAsFixed(0); // 5
这篇关于如何在小数点后将 Dart 中的双精度舍入到给定的精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!