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
Parameter | Optional/Required | Description |
---|---|---|
lowerLimit | required | the lower limit of the range |
upperLimit | required | the 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,
- We create a double variable
num
with the value 5.0, a double variablelowerLimit
with the value 1.0, and a double variableupperLimit
with the value 10.0. - We use the
clamp()
method onnum
withlowerLimit
andupperLimit
as the arguments to clampnum
within the specified range. - 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,
- We create a double variable
num
with the value 15.0, a double variablelowerLimit
with the value 1.0, and a double variableupperLimit
with the value 10.0. - We use the
clamp()
method onnum
withlowerLimit
andupperLimit
as the arguments to clampnum
within the specified range. - 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,
- We create a double variable
num
with the value -5.0, a double variablelowerLimit
with the value -10.0, and a double variableupperLimit
with the value 0.0. - We use the
clamp()
method onnum
withlowerLimit
andupperLimit
as the arguments to clampnum
within the specified range. - 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.