Generate random integer rounded to nearest whole number

Viewed 240

I am wondering how to generate a random integer that gets rounded to nearest whole number, e.g. random number: 436, == 440, or 521, == 520. basically just rounding the random number to the nearest whole number. (JavaScript)

Math.floor(Math.random() * max) + min; //gets random number
//then I want to round the number here, maybe even in the same line as where the number is 
//being generated.
3 Answers

I think this should do the job:

result = Math.round((Math.floor(Math.random() * max) + min) / 10) * 10;

To round a number, you can use Math.floor(n / 10) * 10. Example:

function randomRoundNumber(min, max) {
  return Math.round((Math.floor(Math.random() * (max - min)) + min) / 10) * 10;
}
<button onclick="console.log(randomRoundNumber(parseInt(prompt('min?')),parseInt(prompt('max?'))))">Random number</button>

This sould get the job done

 Math.round((Math.floor(Math.random() * max) + min) / 10) * 10
Related