Dart num clamp()
Syntax & Examples


num.clamp() method

The `clamp` method in Dart returns the number clamped to be within a specified range.


Syntax of num.clamp()

The syntax of num.clamp() method is:

 num clamp(num lowerLimit num upperLimit) 

This clamp() method of num 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

num.clamp() returns value of type num.



✐ Examples

1 Clamping a number within a range

In this example,

  1. We define a variable number with the value 25.
  2. We set the lower limit to 10 and the upper limit to 50.
  3. We use the clamp method to clamp the number within the specified range.
  4. We print the clamped number to standard output.

Dart Program

void main() {
  num number = 25;
  num lowerLimit = 10;
  num upperLimit = 50;
  num clampedNumber = number.clamp(lowerLimit, upperLimit);
  print('Clamped number: $clampedNumber');
}

Output

Clamped number: 25

2 Clamping a number below the lower limit

In this example,

  1. We define a variable number with the value -5.
  2. We set the lower limit to 0 and the upper limit to 10.
  3. We use the clamp method to clamp the number within the specified range.
  4. We print the clamped number to standard output.

Dart Program

void main() {
  num number = -5;
  num lowerLimit = 0;
  num upperLimit = 10;
  num clampedNumber = number.clamp(lowerLimit, upperLimit);
  print('Clamped number: $clampedNumber');
}

Output

Clamped number: 0

3 Clamping a number above the upper limit

In this example,

  1. We define a variable number with the value 7.5.
  2. We set the lower limit to 2.0 and the upper limit to 5.0.
  3. We use the clamp method to clamp the number within the specified range.
  4. We print the clamped number to standard output.

Dart Program

void main() {
  num number = 7.5;
  num lowerLimit = 2.0;
  num upperLimit = 5.0;
  num clampedNumber = number.clamp(lowerLimit, upperLimit);
  print('Clamped number: $clampedNumber');
}

Output

Clamped number: 5

Summary

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