在小数点后如何将Dart中的double舍入到给定的精度? [英] How do you round a double in Dart to a given degree of precision AFTER the decimal point?

查看:2405
本文介绍了在小数点后如何将Dart中的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.

推荐答案

请参阅字符串 toStringAsFixed (整数分数数字)

String toStringAsFixed(int fractionDigits)

返回它的小数点字符串表示形式.

Returns a decimal-point string-representation of this.

在计算字符串表示形式之前,将其转换为double.

Converts this to a double before computing the string representation.

  • 如果此方法的绝对值大于或等于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等于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中的double舍入到给定的精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆