How can I use JavaScript to limit a number between a min/max value?

JavascriptNumbersInteger

Javascript Problem Overview


I want to limit a number between two values, I know that in PHP you can do this:

$number = min(max(intval($number), 1), 20);
// this will make $number 1 if it's lower than 1, and 20 if it's higher than 20

How can I do this in javascript, without having to write multiple if statements and stuff like that? Thanks.

Javascript Solutions


Solution 1 - Javascript

like this

var number = Math.min(Math.max(parseInt(number), 1), 20);

#Live Demo:

function limitNumberWithinRange(num, min, max){
  const MIN = min || 1;
  const MAX = max || 20;
  const parsed = parseInt(num)
  return Math.min(Math.max(parsed, MIN), MAX)
}

alert(
  limitNumberWithinRange(  prompt("enter a number")   )
)

Solution 2 - Javascript

You have at least two options:

You can use a pair of conditional operators (? :):

number = number > 100 ? 100 : number < 0 ? 0 : number;

Or you can combine Math.max and Math.min:

number = Math.min(100, Math.max(0, number));

In both cases, it's relatively easy to confuse yourself, so you might consider having a utility function if you do this in multiple places:

function clamp(val, min, max) {
    return val > max ? max : val < min ? min : val;
}

Then:

number = clamp(number, 0, 100);

Solution 3 - Javascript

Use lodash's clamp method:

_.clamp(22, 1, 20) // Outputs 20

Solution 4 - Javascript

Needs no further explanation:

function clamp(value, min, max) {
    return Math.min(Math.max(value, min), max);
}

Solution 5 - Javascript

Related: https://stackoverflow.com/questions/11409895/whats-the-most-elegant-way-to-cap-a-number-to-a-segment:

> Update for ECMAScript 2017: > > Math.clamp(x, lower, upper) > > But note that as of today, it's a Stage 1 proposal. Until it gets widely supported, you can use a polyfill.

Solution 6 - Javascript

I will share my robust function to enforce whole numbers (because of the integer tag), it has features like optional min/max parameters and -0 protection:

function toInt(val, min, max){
	val=(val*1 || 0);
	val=(val<0 ? Math.ceil(val) : Math.floor(val));
	
	min*=1;
	max*=1;
	
	min=((Number.isNaN(min) ? -Infinity : min) || 0);
	max=((Number.isNaN(max) ? Infinity : max) || 0);
	
	return Math.min(Math.max(val, min), max);
}

Some quick notes:

  • The (... || 0) behind the scenes is dealing with -0 to change it to 0, which is almost always what you want.
  • The min and max parameters are optional. When blank or invalid values are passed, they will turn into -Infinity and Infinity so they silently don't interfere with Math.min() and Math.max().
  • You can change Number.isNaN(x) ECMAScript-6 to x!==x (results in true only for NaN) for more compatibility with really old browsers, but this is simply not necessarily anymore.

Solution 7 - Javascript

You could easily just extend Math by adding your own method...

ES6

Math.minmax = (value, min, max) => Math.min(Math.max(value, min), max);

ES5

Math.minmax = function(value, min, max){
    return Math.min(Math.max(value, min), max);
}

Solution 8 - Javascript

Use Math.min and Math.max.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexandraView Question on Stackoverflow
Solution 1 - JavascriptGovind MalviyaView Answer on Stackoverflow
Solution 2 - JavascriptT.J. CrowderView Answer on Stackoverflow
Solution 3 - JavascriptGregory BolkenstijnView Answer on Stackoverflow
Solution 4 - JavascriptNeuron - Freedom for UkraineView Answer on Stackoverflow
Solution 5 - JavascriptRafeView Answer on Stackoverflow
Solution 6 - Javascriptajax333221View Answer on Stackoverflow
Solution 7 - JavascriptPaul BrowneView Answer on Stackoverflow
Solution 8 - JavascriptFemarefView Answer on Stackoverflow