I have a JS calculation that returns a number. I need a Javascript function that limits that number to a max value. If the number returned by the calculation is greater than Max(a predetermined value) change the number to the Max value. I am clueless where to begin. Need help please.
How do I limit a number, returned by a JS calcualation, to a predetermined Max value?
787 Views Asked by Kenny Salter At
2
There are 2 best solutions below
1
On
You can insert an If statement to check the value of the number and then decide if you want to show the value or an defined value.
const output = document.querySelector('[data-output]')
const button = document.querySelector('[data-button]')
button.addEventListener('click', () => {
const number = Math.floor(Math.random()*10)
if (number <= 5) {
output.innerText = number
} else
output.innerText = 'number over 5'
})
<output data-output></output><br />
<button data-button>Random Number 1-10</button>
You could take
Math.min.