1. 舍弃小数部分(取整)
首先我们来看如何只保留整数位,这里有很多方法可以实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| void main() { double price = 100 / 3;
print("price = $price");
print("price.truncate() = ${price.truncate()}");
print("price.truncateToDouble() = ${price.truncateToDouble()}");
print("price.toInt() = ${price.toInt()}");
print("price.ceil() = ${price.ceil()}");
print("price.ceilToDouble() = ${price.ceilToDouble()}");
print("price.round() = ${price.round()}");
print("price.roundToDouble() = ${price.roundToDouble()}");
final int number = 100 ~/ 3; print("number = $number"); }
|
根据自己的需求,是否需要四舍五入等,选择一个合适的方法即可。
2. 取余
1 2 3 4 5 6 7
| void main() { int a = 15; int b = 2; print(a % b); print(a ~/ b); print(a / b); }
|
3. 保留小数点后 n 位
如果我们想要控制浮点数的精度,想要保留小数点后几位数字,怎么实现?
最简单的是使用 toStringAsFixed()
方法:
1 2 3 4 5 6 7 8 9 10 11 12
| void main() { double price = 100 / 3;
print("price = $price");
print("price.toStringAsFixed = ${price.toStringAsFixed(2)}");
print("price.toStringAsFixed = ${price.toStringAsFixed(5)}"); }
|
注意,toStringAsFixed()
方法会进行四舍五入。
或者也可以使用第三方类库,或者自己写一个函数实现都可以。当然,大多数情况下 toStringAsFixed()
方法都可以满足我们的需求了。