Dart double compareTo()
Syntax & Examples
double.compareTo() method
The `compareTo` method compares the given number to another number.
Syntax of double.compareTo()
The syntax of double.compareTo() method is:
int compareTo(num other)
This compareTo() method of double compares this to other
.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
other | required | the number to compare with |
Return Type
double.compareTo() returns value of type int
.
✐ Examples
1 Compare two positive numbers
In this example,
- We define two doubles,
num1
with a value of5.5
andnum2
with a value of7.7
. - We call the
compareTo
method onnum1
withnum2
as the argument. - We print the comparison result to standard output.
Dart Program
void main() {
double num1 = 5.5;
double num2 = 7.7;
int result = num1.compareTo(num2);
print('Comparison result: $result');
}
Output
Comparison result: -1
2 Compare two negative numbers
In this example,
- We define two doubles,
num1
with a value of-3.3
andnum2
with a value of-1.1
. - We call the
compareTo
method onnum1
withnum2
as the argument. - We print the comparison result to standard output.
Dart Program
void main() {
double num1 = -3.3;
double num2 = -1.1;
int result = num1.compareTo(num2);
print('Comparison result: $result');
}
Output
Comparison result: -1
3 Compare two equal numbers
In this example,
- We define two doubles,
num1
andnum2
, both with a value of10.0
. - We call the
compareTo
method onnum1
withnum2
as the argument. - We print the comparison result to standard output.
Dart Program
void main() {
double num1 = 10.0;
double num2 = 10.0;
int result = num1.compareTo(num2);
print('Comparison result: $result');
}
Output
Comparison result: 0
Summary
In this Dart tutorial, we learned about compareTo() method of double: the syntax and few working examples with output and detailed explanation for each example.