4 ways to convert Double to Int in Flutter & Dart

Last updated on July 11, 2021 The Plumber Loading... Post a comment

4 common ways to convert a double to an integer in Flutter and Dart.

Using toInt()

The toInt() method will truncate a double to an integer and return a result whose type is int. In other words, the numbers will be rounded down (e.g. 3.99 and 3.1 both return 3).

Example:

void main(){
  double x = 3.94;
  var y = x.toInt();
  print(y);
  print(y.runtimeType);
}

Output:

3
int

Using round()

The round() method returns the closest integer to the double.

Example:

void main(){
  double a = 9.6;
  var b = a.round();
  print(b);
  print(b.runtimeType);
}

Output:

10
int

Using ceil()

The ceil() method returns the smallest integer that is equal or greater than the given double.

Example:

void main(){
  double c = 5.1;
  var d = c.ceil();
  print(d);
  print(d.runtimeType);
}

Output:

6
int

Using floor()

The floor() method returns the greatest integer not greater than the given double.

Example:

void main(){
  double k = 1000.9;
  var j = k.floor();
  print(j);
  print(j.runtimeType);
}

Output:

1000
int

Conclusion

We’ve gone through 4 different techniques to convert a double to an integer in Dart and Flutter. You can choose from the method that fits your use case to solve your problem. Flutter is awesome and provides a lot of amazing features. Continue learning and exploring more by taking a look at the following article:

You can also take a tour around our Flutter topic page or Dart topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles