How to cap a number to a segment with JavaScript?

Sometimes, we want to cap a number to a segment with JavaScript.

In this article, we’ll look at how to cap a number to a segment with JavaScript.

How to cap a number to a segment with JavaScript?

To cap a number to a segment with JavaScript, we can use the Math.max and Math.min methods.

For instance, we write

const n = Math.max(min, Math.min(number, max));

to use Math.min(number, max) to get the min of number and max.

And then we call Math.amx with min and the number returned by Math.min(number, max) to cap the number between min and max.

If number is less than max and bigger than min, then it’ll be returned.

Conclusion

To cap a number to a segment with JavaScript, we can use the Math.max and Math.min methods.