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

ParameterOptional/RequiredDescription
otherrequiredthe number to compare with

Return Type

double.compareTo() returns value of type int.



✐ Examples

1 Compare two positive numbers

In this example,

  1. We define two doubles, num1 with a value of 5.5 and num2 with a value of 7.7.
  2. We call the compareTo method on num1 with num2 as the argument.
  3. 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,

  1. We define two doubles, num1 with a value of -3.3 and num2 with a value of -1.1.
  2. We call the compareTo method on num1 with num2 as the argument.
  3. 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,

  1. We define two doubles, num1 and num2, both with a value of 10.0.
  2. We call the compareTo method on num1 with num2 as the argument.
  3. 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.