【问题标题】:Where is Math.round() in Dart?Dart 中的 Math.round() 在哪里?
【发布时间】:2021-08-16 15:27:11
【问题描述】:

我没有看到在 Dart 中对数字进行四舍五入的任何方法?

import 'dart:math';

main() {
  print(Math.round(5.5)); // Error!
}

http://api.dartlang.org/docs/bleeding_edge/dart_math.html

【问题讨论】:

    标签: dart


    【解决方案1】:

    是的,有办法做到这一点。 num 类有一个名为 round() 的方法:

    var foo = 6.28;
    print(foo.round()); // 6
    
    var bar = -6.5;
    print(bar.round()); // -7
    

    【讨论】:

      【解决方案2】:

      在 Dart 中,一切都是对象。所以,当你声明一个数字时,例如,你可以通过round method from the num class将它四舍五入,下面的代码将打印6

      num foo = 5.6;
      print(foo.round()); //prints 6
      

      在你的情况下,你可以这样做:

      main() {
          print((5.5).round());
      }
      

      【讨论】:

        【解决方案3】:

        这个公式会帮助你

        int a = 500;
        int b = 250;
        int c;
        
        c = a ~/ b;
        

        【讨论】:

          【解决方案4】:

          2021 年 3 月更新:

          round() 方法已移至 https://api.dart.dev/stable/2.12.2/dart-core/num/round.html。以上链接都是错误的。

          【讨论】:

            【解决方案5】:

            也许这在特定情况下会有所帮助, 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
            }
            

            【讨论】:

              猜你喜欢
              • 2013-04-22
              • 2015-06-26
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2012-07-25
              • 2019-01-20
              相关资源
              最近更新 更多