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

ParameterOptional/RequiredDescription
otherrequiredThe other number to compare to.

Return Type

num.compareTo() returns value of type int.



✐ Examples

1 Comparing two numbers

In this example,

  1. We define two variables, number1 and number2, with values 10 and 5 respectively.
  2. We use the compareTo method to compare number1 to number2 and store the result in result.
  3. 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,

  1. We define two variables, number1 and number2, both with the value -3.8.
  2. We use the compareTo method to compare number1 to number2 and store the result in result.
  3. 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,

  1. We define two variables, number1 with the value 7.0 and number2 with the value 10.
  2. We use the compareTo method to compare number1 to number2 and store the result in result.
  3. 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.