How to Restrict a Number to a Certain Range in TypeScript ?
Last Updated :
05 Jan, 2024
Restricting a number to a certain range in TypeScript means ensuring that a numerical value falls within specific bounds or limits. This process, often referred to as “clamping” or “bounding,” prevents a number from going below a minimum value or exceeding a maximum value.
For example, if you have a requirement that a variable representing a person’s age should always be between 0 and 100, restricting the number to this range ensures that the age remains a valid value.
Below are the approaches used to restrict a number to a certain range:
Approach 1: Using Math.min
and Math.max
In this we use Math.min
to ensure the value isn’t below the minimum and Math.max
to cap it at the maximum.
Example: In this example, we are using Math.min
and Math.max.
Javascript
function numbers(value: number, min: number, max: number):
{ result: number, message: string } {
const num = Math.min(Math.max(value, min), max);
let message: string;
if (num === value) {
message = `Number ${value} is within
the range of ${min} to ${max}.`;
} else if (num === min) {
message = `Number ${value} is below
the lower limit of ${min}.`;
} else {
message = `Number ${value} exceeds
the upper limit of ${max}.`;
}
return { result: num, message };
}
let value: number = 15;
let min: number = 5;
let max: number = 10;
let resultObject = numbers(value, min, max);
console.log(resultObject.result);
console.log(resultObject.message);
|
Output:
10
Number 15 exceeds the upper limit of 10.
Approach 2: Using Ternary Operator
In this we use ternary operator to check and limit the value within the specified range.
Example: In this example, we are using Ternary Operator.
Javascript
function numbers(value: number, min: number, max: number):
{ result: number, message: string } {
const result = value < min ? min :
value > max ? max : value;
const message =
result === value
? `Number ${value} is within
the range of ${min} to ${max}.`
: result === min
? `Number ${value} is below the
lower limit of ${min}.`
: `Number ${value} exceeds the
upper limit of ${max}.`;
return { result, message };
}
let value: number = 15;
let min: number = 5;
let max: number = 10;
let resultObject = numbers(value, min, max);
console.log(resultObject.result);
console.log(resultObject.message);
|
Output:
10
Number 15 exceeds the upper limit of 10.
Share your thoughts in the comments
Please Login to comment...