【问题标题】:How do I avoid using 'as' when casting from double to int?从double转换为int时如何避免使用'as'?
【发布时间】:2019-03-02 08:10:00
【问题描述】:

我正在尝试计算一个百分比值,其中countsize 是整数:

var percent = count * 100 / size as int;

但我收到一条警告,上面写着“避免使用 as”。我想将百分比设为整数类型。我怎样才能重写它以避免使用'as'?

【问题讨论】:

标签: dart


【解决方案1】:

您可以使用截断除法运算符~/ 来做您想做的事情。

var percent = count * 100 ~/ size;

【讨论】:

    【解决方案2】:

    哎呀,原来我不能使用“as int”,因为 int 不是 double 的子类。相反,我需要使用 round() 方法,该方法返回这样的 int:

        var percent = (count * 100 / size).round();
    

    【讨论】:

      【解决方案3】:

      除了 Alexandre Ardhuin 的回答:

      据我所知,dart 在投射方面不是那么灵活,因此不建议使用(在这种情况下甚至不允许使用)。

      您可以使用 round() 函数:

      int count = 1;
      int size = 3;
      var percent = (count * 100 / size);
      print(percent);
      
      int asInt = percent.round();
      print(asInt);
      

      或者如果你想要典型的interger rounding,请使用floor()

      int count = 1;
      int size = 3;
      var percent = (count * 100 / size);
      print(percent);
      
      int asInt = percent.floor();
      print(asInt);
      

      注意: 在这些示例中,percent 是一个双精度值,可以存储起来供以后使用。


      为了完整起见,包括ceil
      int count = 2;
      int size = 3;
      
      var percent = (count * 100 / size);
      print(percent);
      
      int asIntRound = percent.round();
      print(asIntRound);
      
      int asIntFloor = percent.floor();
      print(asIntFloor);
      
      int asIntCeil = percent.ceil();
      print(asIntCeil);
      

      输出:

      66.66666666666667
      67
      66
      67
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-10-20
        • 2020-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-16
        相关资源
        最近更新 更多