Open In App

How to limit a number between a min/max value in JavaScript ?

Last Updated : 23 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

We can limit a number between a min/max value using the is-else condition and using the Math.min and Math.max methods of JavaScript.

Below are the approaches to limit a number between a min/max value in JavaScript:

Using the if-else condition

This JavaScript function checkNumber(n) ensures that an input number n is within the range of 0 to 100.

  • Convert to number: The input n is converted to a number using Number(n).
  • Check below 0: If n is less than 0, a message is logged to the console instructing the user to enter a number between 0 and 100, and the value is set to 0.
  • Check above 100: If n is greater than 100, it logs the same message and sets n to 100.
  • Valid number: If n is valid, it logs the entered number.

Example: The below code uses if-else conditions to limit the value of the entered number.

JavaScript
function checkNumber(n) {
    n = Number(n);
    if (n < 0) {
        console.log('Type number between 0-100');
        n = 0;
    } else if (n > 100) {
        console.log('Type number between 0-100');
        n = 100;
    } else {
        console.log('Valid number: ' + n);
    }
}

checkNumber(50);  

Output
Valid number: 50

Using the Math.min() and Math.max() methods

The approach ensures a number is within the range [0, 100] by using input conversion and value clamping:

  • Input Conversion: checkRange() converts the input into a number using Number() to handle possible non-numeric values.
  • Range Clamping: It applies Math.max(0, n) to ensure the number is at least 0 and Math.min(100, n) to ensure it doesn’t exceed 100.
  • Test and Output: checkNumber() tests this logic by passing 150, which is clamped to 100. Both the original and clamped values are logged for comparison.

Example: The below example illustrates the use of the Math.min() and Math.max() methods to limit the entered number.

JavaScript
// Function to check if a number is within the range [0, 100]
function checkRange(number) {
    let n = Number(number);
    n = Math.min(100, Math.max(0, n)); 
    return n;
}

function checkNumber() {
    const inputNumber = 150;  
    const rangedNumber = checkRange(inputNumber);   
    console.log("Original number: " + inputNumber);
    console.log("Number ranged to: " + rangedNumber); 
}

checkNumber();

Output
Original number: 150
Number ranged to: 100

Next Article

Similar Reads