在Dart中,有没有一种快速的方法可以将int转换为double? [英] In Dart is there a quick way to convert int to double?
问题描述
非常简单的问题。我有无用的课程:
Very simple issue. I have the useless class:
class Useless{
double field;
Useless(this.field);
}
然后我犯下了致命的罪,并称 new Useless (0);
在检查模式下(这是我运行测试的方式)会爆炸,因为'int'不是'double'类型的子类型。
I then commit the mortal sin and call new Useless(0);
In checked mode (which is how I run my tests) that blows up, because 'int' is not a subtype of type 'double'.
现在,如果我使用 new Useless(0.0)
可以使用,但是说实话,我花了很多时间进行纠正我的测试到处都放置了.0s,我觉得很愚蠢。
Now, it works if I use new Useless(0.0)
, but honestly I spend a lot of time correcting my tests putting .0s everywhere and I feel pretty dumb doing that.
作为一种临时措施,我将构造函数重写为:
As a temporary measure I rewrote the constructor as:
class Useless{
double field;
Useless(num input){
field = input.toDouble();
}
}
但这很丑陋,如果经常调用,恐怕会很慢。有更好的方法吗?
But that's ugly and I am afraid slow if called often. Is there a better way to do this?
推荐答案
在Dart 2.1 中,整数文字可直接用于 double
是预期的。 (请参见
In Dart 2.1, integer literals may be directly used where double
is expected. (See https://github.com/dart-lang/sdk/issues/34355.)
请注意,这仅适用于文字。 int
变量仍不会自动提升为 double
,因此代码如下:
Note that this applies only to literals. int
variables still won't be automatically promoted to double
, so code like:
double reciprocal(double d) => 1 / d;
int x = 42;
reciprocal(x);
将会失败,并且您需要这样做:
would fail, and you'd need to do:
reciprocal(x.toDouble());
这篇关于在Dart中,有没有一种快速的方法可以将int转换为double?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!