给定一个double,我希望将它四舍五入到小数点后的给定精度点数,类似于PHP的round()函数。

我能在Dart文档中找到的最接近的东西是double.toStringAsPrecision(),但这不是我所需要的,因为它包括了精度总分中小数点前的数字。

例如,使用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

随着数字大小的增加,小数点后的精度也相应降低。


当前回答

您可以简单地将该值乘以100,然后四舍五入,然后再除以100。

(number * 100).round() / 100.0;

其他回答

上述解决方案并不适用于所有情况。对我的问题有效的方法是这个解决方案,它将你的数字四舍五入(0.5到1或0.49到0),并且不带任何小数:

输入:12.67

double myDouble = 12.67;
var myRoundedNumber; // Note the 'var' datatype

// Here I used 1 decimal. You can use another value in toStringAsFixed(x)
myRoundedNumber = double.parse((myDouble).toStringAsFixed(1));
myRoundedNumber = myRoundedNumber.round();

print(myRoundedNumber);

输出:13

这种联系也有其他的解决方案

double value = 2.8032739273;
String formattedValue = value.toStringAsFixed(3);

如果你想在文本中舍入double值。

文本(“$ {carpetprice.toStringAsFixed(3)}”,),

我使用toStringAsFixed()方法将一个数字四舍五入到小数点后的特定数字 例:

double num = 22.48132906

当我四舍五入到像这样的两个数字时:

print(num.toStringAsFixed(2)) ;

结果是22.48

当我四舍五入到一个数字时,它显示出22.5

效果很好

var price=99.012334554
price = price.roundTodouble();
print(price); // 99.01