The `toInt` method is used to truncate a `num` (number) to an integer and returns the result as an `int` (integer). It is commonly used when you need to convert a floating-point number to a whole number, discarding the decimal part.
The syntax of double.toInt() method is:
int toInt()
This toInt() method of double truncates this num
to an integer and returns the result as an int
.
double.toInt() returns value of type int
.
In this example,
num
with the value 3.14.toInt()
method to truncate the double to an integer, stored in integerNum
.void main() {
double num = 3.14;
int integerNum = num.toInt();
print('Truncated value of $num to int: $integerNum');
}
Truncated value of 3.14 to int: 3
In this example,
numbers
with values [1.2, 3.4, 5.6].map()
with toInt()
to truncate each double to an integer in integerList
.void main() {
List<double> numbers = [1.2, 3.4, 5.6];
List<int> integerList = numbers.map((num) => num.toInt()).toList();
print('Truncated list of numbers: $integerList');
}
Truncated list of numbers: [1, 3, 5]
In this example,
strings
with values ['apple', 'banana', 'cherry'].map()
with length.toInt()
to truncate each string's length to an integer in stringLengths
.void main() {
List<String> strings = ['apple', 'banana', 'cherry'];
List<int> stringLengths = strings.map((str) => str.length.toInt()).toList();
print('Lengths of strings: $stringLengths');
}
Lengths of strings: [5, 6, 6]
In this Dart tutorial, we learned about toInt() method of double: the syntax and few working examples with output and detailed explanation for each example.