The `clamp` method in Dart returns the given number clamped to be within a specified range defined by the lower and upper limits.
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
.
Parameter | Optional/Required | Description |
---|---|---|
lowerLimit | required | the lower limit of the range |
upperLimit | required | the upper limit of the range |
double.clamp() returns value of type num
.
In this example,
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.clamp()
method on num
with lowerLimit
and upperLimit
as the arguments to clamp num
within the specified range.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');
}
Clamped value of 5: 5
In this example,
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.clamp()
method on num
with lowerLimit
and upperLimit
as the arguments to clamp num
within the specified range.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');
}
Clamped value of 15: 10
In this example,
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.clamp()
method on num
with lowerLimit
and upperLimit
as the arguments to clamp num
within the specified range.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');
}
Clamped value of -5: -5
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.