Dart double toInt()
Syntax & Examples
double.toInt() method
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.
Syntax of double.toInt()
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
.
Return Type
double.toInt() returns value of type int
.
✐ Examples
1 Truncate a Double to Integer
In this example,
- We declare a double variable
num
with the value 3.14. - We use the
toInt()
method to truncate the double to an integer, stored inintegerNum
. - We print the truncated integer to standard output.
Dart Program
void main() {
double num = 3.14;
int integerNum = num.toInt();
print('Truncated value of $num to int: $integerNum');
}
Output
Truncated value of 3.14 to int: 3
2 Truncate a List of Doubles to Integers
In this example,
- We create a list of doubles
numbers
with values [1.2, 3.4, 5.6]. - We use
map()
withtoInt()
to truncate each double to an integer inintegerList
. - We print the truncated list of integers to standard output.
Dart Program
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');
}
Output
Truncated list of numbers: [1, 3, 5]
3 Truncate List of Strings' Lengths to Integers
In this example,
- We create a list of strings
strings
with values ['apple', 'banana', 'cherry']. - We use
map()
withlength.toInt()
to truncate each string's length to an integer instringLengths
. - We print the lengths of strings as integers to standard output.
Dart Program
void main() {
List<String> strings = ['apple', 'banana', 'cherry'];
List<int> stringLengths = strings.map((str) => str.length.toInt()).toList();
print('Lengths of strings: $stringLengths');
}
Output
Lengths of strings: [5, 6, 6]
Summary
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.