【发布时间】:2021-08-16 15:27:11
【问题描述】:
我没有看到在 Dart 中对数字进行四舍五入的任何方法?
import 'dart:math';
main() {
print(Math.round(5.5)); // Error!
}
【问题讨论】:
标签: dart
我没有看到在 Dart 中对数字进行四舍五入的任何方法?
import 'dart:math';
main() {
print(Math.round(5.5)); // Error!
}
【问题讨论】:
标签: dart
是的,有办法做到这一点。 num 类有一个名为 round() 的方法:
var foo = 6.28;
print(foo.round()); // 6
var bar = -6.5;
print(bar.round()); // -7
【讨论】:
在 Dart 中,一切都是对象。所以,当你声明一个数字时,例如,你可以通过round method from the num class将它四舍五入,下面的代码将打印6
num foo = 5.6;
print(foo.round()); //prints 6
在你的情况下,你可以这样做:
main() {
print((5.5).round());
}
【讨论】:
这个公式会帮助你
int a = 500;
int b = 250;
int c;
c = a ~/ b;
【讨论】:
2021 年 3 月更新:
round() 方法已移至 https://api.dart.dev/stable/2.12.2/dart-core/num/round.html。以上链接都是错误的。
【讨论】:
也许这在特定情况下会有所帮助, floor() 将向负无穷方向舍入
https://api.dart.dev/stable/2.13.4/dart-core/num/floor.html
void main() {
var foo = 3.9;
var bar = foo.floor();
print(bar);//prints 3
}
【讨论】: