Dart num toInt()
Syntax & Examples


num.toInt() method

The `toInt` method in Dart truncates this number to an integer and returns the result as an integer.


Syntax of num.toInt()

The syntax of num.toInt() method is:

 int toInt() 

This toInt() method of num truncates this num to an integer and returns the result as an int.

Return Type

num.toInt() returns value of type int.



✐ Examples

1 Truncating a decimal number

In this example,

  1. We create a num variable number1 with the value 5.6 and another variable number2 with the value -3.2.
  2. We use the toInt() method to truncate them to integers.
  3. We then print the truncated values to standard output.

Dart Program

void main() {
  num number1 = 5.6;
  num number2 = -3.2;
  int result1 = number1.toInt();
  int result2 = number2.toInt();
  print('Truncated value of $number1: $result1');
  print('Truncated value of $number2: $result2');
}

Output

Truncated value of 5.6: 5
Truncated value of -3.2: -3

2 Truncating a decimal number with fractional part

In this example,

  1. We create a num variable number with the value 10.9.
  2. We use the toInt() method to truncate it to an integer.
  3. We then print the truncated value to standard output.

Dart Program

void main() {
  num number = 10.9;
  int result = number.toInt();
  print('Truncated value of $number: $result');
}

Output

Truncated value of 10.9: 10

Summary

In this Dart tutorial, we learned about toInt() method of num: the syntax and few working examples with output and detailed explanation for each example.