In Dart is there a quick way to convert int to double?

CarrKnight picture CarrKnight · Oct 17, 2014 · Viewed 49.6k times · Source

Very simple issue. I have a 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?

Answer

Ronen Rabinovici picture Ronen Rabinovici · Aug 2, 2018

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