如何在飞镖中将双精度值四舍五入到小数点后两位?
How to round the double value upto two decimal points in dart?
我已经创建了这个被调用来执行功能和进行计算的方法,但是 return 一些计算的双精度格式的数字最多超过 10 个小数点。我怎样才能让这段代码只显示最多 2 或 3 个小数点?
getProductPrice(int productID) {
var cart = cartlist.firstWhere((cart) => cart.product.id == productID,
orElse: () => null);
if (cart != null) {
var price= (cart.count)*(cart.product.price);
return price;
notifyListeners();
} else {
return 0.0;
}
}
您可以使用 String toStringAsFixed(int fractionDigits)
Returns 这个的小数点字符串表示。
在计算字符串表示之前将 this
转换为双精度数。
如果其绝对值大于或等于 10^21,则此方法 returns 由 this.toStringAsExponential() 计算的指数表示。否则,结果是最接近的字符串表示形式,小数点后正好有 fractionDigits 数字。如果 fractionDigits 等于 0,则省略小数点。
参数fractionDigits必须是一个整数满足: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
有关更多信息,请查看官方 documentation。
我已经创建了这个被调用来执行功能和进行计算的方法,但是 return 一些计算的双精度格式的数字最多超过 10 个小数点。我怎样才能让这段代码只显示最多 2 或 3 个小数点?
getProductPrice(int productID) {
var cart = cartlist.firstWhere((cart) => cart.product.id == productID,
orElse: () => null);
if (cart != null) {
var price= (cart.count)*(cart.product.price);
return price;
notifyListeners();
} else {
return 0.0;
}
}
您可以使用 String toStringAsFixed(int fractionDigits)
Returns 这个的小数点字符串表示。
在计算字符串表示之前将
this
转换为双精度数。如果其绝对值大于或等于 10^21,则此方法 returns 由 this.toStringAsExponential() 计算的指数表示。否则,结果是最接近的字符串表示形式,小数点后正好有 fractionDigits 数字。如果 fractionDigits 等于 0,则省略小数点。
参数fractionDigits必须是一个整数满足: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
有关更多信息,请查看官方 documentation。