How to do Integer division in dart | Flutter By Example

In Dart, the Division operator / is used to divide the numbers.

For example, two integer numbers are divided with the / operator, and the result is stored into an integer.

void main() {
  int first = 10;
  int second = 2;
  int result;

  result = first / second;
}

The above code throws a compilation error Error: A value of type ‘double’ can’t be assigned to a variable of type ‘int’.

Int is a number without decimals, and double is a number with decimals.

Since the division operator always returns double values. if you assign the typed int variable with the result, It gives a compilation error.

There are a number of ways to fix this.

Dart number division examples

The first way, use truncating division operator(~/) operator to return the int type only.

/ operator always results in a double value. the truncating division operator(~/) results in int number by truncating double decimal values

Here is an example program

void main() {
  int first = 10;
  int second = 2;
  int result;

  result = first ~/ second;
  print(result);
  print(result.runtimeType);
}

Output:

5
int

Second-way using return result type as var or double with division operator.

In this example, use the division operator to return of dynamic variable declared with var or double instead of int. the dynamic variable can be of any type such as int and double.

Here is an example program

void main() {
  int first = 10;
  int second = 2;
  int result;

  result = first ~/ second;
  print(result);
  print(result.runtimeType);
}

Output:

5.5
double

The third way is using num type instead of int.

int and double are subclass of num. so use the result variable of type num Here is an example program

void main() {
  int first = 11;
  int second = 2;
  num result;

  result = first / second;
  print(result);
  print(result.runtimeType);
}

Output:

5.5
double

The fourth way, use floor or ceil to truncate the decimal part.

floor() method returns a lower int number, which is less than the result double value. ceil() method returns an upper int number that is greater than the result double value

void main() {
  int first = 11;
  int second = 2;
  int result;
  int result1;

  result = (first / second).floor();
  result1 = (first / second).ceil();

  print(result);
  print(result1);
}

Output

5
6

Conclusion

To summarize, Since integer division always returns double, assigning to int results a compilation error. Discussed multiple ways to avoid this