How to Convert Int to Double ??

· 3 min read
How to Convert Int to Double
How to Convert Int to Double

So in Dart 2.1, integer literals may be directly used where double is expected. See https://github.com/dart-lang/sdk/issues/34355. In this article, we walk through How to Convert Int to Double in Dart.

How to Convert Int to 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());

Simply toDouble()

Example:

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

So you can also use:

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

From this attempt:

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

So 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 initializers is:

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

I’m using a combination:

static double checkDouble(dynamic value) {
  if (value is String) {
    return double.parse(value);
  } else if (value is int) {
    return 0.0 + value;
  } else {
    return value;
  }
}

So stay connected for type ‘int’ is not a subtype of type ‘double’ in flutter, convert string to double dart, string to double in flutter, and flutter convert string into int.

Conclusion:

Thanks for being with us on a flutter journey !!! Hope you like the article!!

Don’t forget to check How to Make Fullscreen Flutter Application.

So Keep Learning !!! Keep Fluttering !!!

Do leave your valuable feedback /questions in the comments. we would be happy to help.

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Leave a Reply