Dart round a figure but as a double

139

Solution 1

double number = 84.5;
double answer = (number * 2.3).roundToDouble(); // 194.0

Solution 2

CopsOnRoad's answer is the most direct way, but in general the way to convert an int to a double is to use int.toDouble:

double number = 84.5;

double coke = (number * 2.3).round().toDouble();

Using as double doesn't work because as changes what type the object is treated as but doesn't change the underlying object.

Share:
139
Hasen
Author by

Hasen

Updated on December 13, 2022

Comments

  • Hasen
    Hasen over 1 year

    I want to multiply a figure and then have it rounded to remove any decimal places but returned as a double, rather than an int since that is what I need.

    I've tried this:

    double number = 84.5;
    
    double coke = (number * 2.3).round()) as double;
    

    and this:

    double coke = double.parse(number * 2.3).round());
    

    But I can't get it to be a double, it just throws errors. The value would be 194.35 in this case and I want it to be 194.0.

  • Hasen
    Hasen almost 5 years
    Wow I did not know about that. Works perfectly, thanks.