Dart int clamp()
Syntax & Examples
int.clamp() method
The `clamp` method in Dart's `int` class clamps this number to be within the specified range defined by lowerLimit and upperLimit.
Syntax of int.clamp()
The syntax of int.clamp() method is:
num clamp(num lowerLimit num upperLimit)
This clamp() method of int returns this num clamped to be in the range lowerLimit-upperLimit.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
lowerLimit | required | The lower limit of the range to clamp this number to. |
upperLimit | required | The upper limit of the range to clamp this number to. |
Return Type
int.clamp() returns value of type num
.
✐ Examples
1 Clamped number
In this example,
- We create an integer variable
num
with the value 5. - We use the
clamp()
method to clamp it within the range of 1 to 10. - We then print the clamped number to standard output.
Dart Program
void main() {
int num = 5;
int clampedNum = num.clamp(1, 10);
print('Clamped num: $clampedNum');
}
Output
Clamped num: 5
2 Clamped character code
In this example,
- We create an integer variable
charCode
by getting the character code for 'B'. - We use the
clamp()
method to clamp it within the character codes of 'A' to 'Z'. - We then print the clamped character code to standard output.
Dart Program
void main() {
int charCode = 'B'.codeUnitAt(0);
int clampedCode = charCode.clamp('A'.codeUnitAt(0), 'Z'.codeUnitAt(0));
print('Clamped character code: $clampedCode');
}
Output
Clamped character code: 66
3 Clamped text length
In this example,
- We create a string variable
text
with the value 'Hello'. - We get its length and then use the
clamp()
method to clamp it within the range of 1 to 10. - We then print the clamped text length to standard output.
Dart Program
void main() {
String text = 'Hello';
int clampedLength = text.length.clamp(1, 10);
print('Clamped text length: $clampedLength');
}
Output
Clamped text length: 5
Summary
In this Dart tutorial, we learned about clamp() method of int: the syntax and few working examples with output and detailed explanation for each example.