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
Parameter | Optional/Required | Description |
---|---|---|
lowerLimit | required | The lower limit of the range. |
upperLimit | required | The 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,
- We define a variable
number
with the value 25. - We set the lower limit to 10 and the upper limit to 50.
- We use the
clamp
method to clamp the number within the specified range. - 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,
- We define a variable
number
with the value -5. - We set the lower limit to 0 and the upper limit to 10.
- We use the
clamp
method to clamp the number within the specified range. - 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,
- We define a variable
number
with the value 7.5. - We set the lower limit to 2.0 and the upper limit to 5.0.
- We use the
clamp
method to clamp the number within the specified range. - 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.