Dart num compareTo()
Syntax & Examples
num.compareTo() method
The `compareTo` method in Dart compares this number to another number.
Syntax of num.compareTo()
The syntax of num.compareTo() method is:
int compareTo(num other)
This compareTo() method of num compares this to other.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
other | required | The other number to compare to. |
Return Type
num.compareTo() returns value of type int
.
✐ Examples
1 Comparing two numbers
In this example,
- We define two variables,
number1
andnumber2
, with values 10 and 5 respectively. - We use the
compareTo
method to comparenumber1
tonumber2
and store the result inresult
. - We print the comparison result to standard output.
Dart Program
void main() {
num number1 = 10;
num number2 = 5;
int result = number1.compareTo(number2);
print('Comparison result: $result');
}
Output
Comparison result: 1
2 Comparing equal numbers
In this example,
- We define two variables,
number1
andnumber2
, both with the value -3.8. - We use the
compareTo
method to comparenumber1
tonumber2
and store the result inresult
. - We print the comparison result to standard output.
Dart Program
void main() {
num number1 = -3.8;
num number2 = -3.8;
int result = number1.compareTo(number2);
print('Comparison result: $result');
}
Output
Comparison result: 0
3 Comparing numbers with different values
In this example,
- We define two variables,
number1
with the value 7.0 andnumber2
with the value 10. - We use the
compareTo
method to comparenumber1
tonumber2
and store the result inresult
. - We print the comparison result to standard output.
Dart Program
void main() {
num number1 = 7.0;
num number2 = 10;
int result = number1.compareTo(number2);
print('Comparison result: $result');
}
Output
Comparison result: -1
Summary
In this Dart tutorial, we learned about compareTo() method of num: the syntax and few working examples with output and detailed explanation for each example.