Dart double clamp()
Syntax & Examples


double.clamp() method

The `clamp` method in Dart returns the given number clamped to be within a specified range defined by the lower and upper limits.


Syntax of double.clamp()

The syntax of double.clamp() method is:

 num clamp(num lowerLimit num upperLimit) 

This clamp() method of double returns this num clamped to be in the range lowerLimit-upperLimit.

Parameters

ParameterOptional/RequiredDescription
lowerLimitrequiredthe lower limit of the range
upperLimitrequiredthe upper limit of the range

Return Type

double.clamp() returns value of type num.



✐ Examples

1 Clamp a number within a specified range

In this example,

  1. We create a double variable num with the value 5.0, a double variable lowerLimit with the value 1.0, and a double variable upperLimit with the value 10.0.
  2. We use the clamp() method on num with lowerLimit and upperLimit as the arguments to clamp num within the specified range.
  3. We then print the clamped value to standard output.

Dart Program

void main() {
  double num = 5.0;
  double lowerLimit = 1.0;
  double upperLimit = 10.0;
  double clamped = num.clamp(lowerLimit, upperLimit);
  print('Clamped value of $num: $clamped');
}

Output

Clamped value of 5: 5

2 Clamp a number exceeding the upper limit

In this example,

  1. We create a double variable num with the value 15.0, a double variable lowerLimit with the value 1.0, and a double variable upperLimit with the value 10.0.
  2. We use the clamp() method on num with lowerLimit and upperLimit as the arguments to clamp num within the specified range.
  3. We then print the clamped value to standard output.

Dart Program

void main() {
  double num = 15.0;
  double lowerLimit = 1.0;
  double upperLimit = 10.0;
  double clamped = num.clamp(lowerLimit, upperLimit);
  print('Clamped value of $num: $clamped');
}

Output

Clamped value of 15: 10

3 Clamp a number below the lower limit

In this example,

  1. We create a double variable num with the value -5.0, a double variable lowerLimit with the value -10.0, and a double variable upperLimit with the value 0.0.
  2. We use the clamp() method on num with lowerLimit and upperLimit as the arguments to clamp num within the specified range.
  3. We then print the clamped value to standard output.

Dart Program

void main() {
  double num = -5.0;
  double lowerLimit = -10.0;
  double upperLimit = 0.0;
  double clamped = num.clamp(lowerLimit, upperLimit);
  print('Clamped value of $num: $clamped');
}

Output

Clamped value of -5: -5

Summary

In this Dart tutorial, we learned about clamp() method of double: the syntax and few working examples with output and detailed explanation for each example.