Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a double to an int in Dart?

Tags:

dart

People also ask

Can you go from double to int?

round() method converts the double to an integer by rounding off the number to the nearest integer. For example – 10.6 will be converted to 11 using Math. round() method and 1ill be converted to 10 using typecasting or Double. intValue() method.


Round it using the round() method:

int calc_ranks(ranks) {
    double multiplier = .5;
    return (multiplier * ranks).round();
}

You can use any of the following.

double d = 20.5;

int i = d.toInt(); // i = 20
int i = d.round(); // i = 21
int i = d.ceil();  // i = 21
int i = d.floor(); // i = 20

You can simply use toInt() to convert a num to an int.

int calc_ranks(ranks)
{
  double multiplier = .5;
  return (multiplier * ranks).toInt();
}

Note that to do exactly the same thing you can use the Truncating division operator :

int calc_ranks(ranks) => ranks ~/ 2;

Dart round double to int

Using round() method, we can get an integer closest to a double.

For example:

int num1 = (2.3).round();
// 2

int num2 = (2.5).round();
// 3

int num3 = (-2.3).round();
// -2

int num4 = (-2.5).round();
// -3

You can also try to those methods convert double to int in a Flutter

  double x = 2.5;
 
  int a = x.toInt();
  int b = x.truncate();
  int c = x.round();
  int d = x.ceil();
  int e = x.floor();
 
  print(a); // 2
  print(b); // 2
  print(c); // 3
  print(d); // 3
  print(e); // 2