In Dart is there a quick way to convert int to dou

2019-04-18 19:12发布

问题:

Very simple issue. I have the useless class:

class Useless{
  double field;
  Useless(this.field);
}

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'.

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?

回答1:

In Dart 2.1, integer literals may be directly used where double is expected. (See https://github.com/dart-lang/sdk/issues/34355.)

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);

will still fail, and you'll need to do:

reciprocal(x.toDouble());


回答2:

Simply toDouble()

Example:

int intVar = 5;
double doubleVar = intVar.toDouble();

Thanks to @jamesdlin who actually gave this answer in a comment to my previous answer...



回答3:

You can also use:

int x = 15;
double y = x + .0;


回答4:

There's no better way to do this than the options you included :(

I get bitten by this lots too, for some reason I don't get any warnings in the editor and it just fails at runtime; mighty annoying :(



回答5:

From this attempt:

class Useless{
  double field;
  Useless(num input){
    field = input.toDouble();
  }
}

You can use the parse method of the double class which takes in a string.

class Useless{
  double field;
  Useless(num input){
    field = double.parse(input.toString()); //modified line
  }
}

A more compact way of writing the above class using constructor's initialisers is:

class Useless{
  double _field;
  Useless(double field):_field=double.parse(field.toString());
}


标签: dart