Home > other >  Generate random integer rounded to nearest whole number
Generate random integer rounded to nearest whole number

Time:02-11

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.

CodePudding user response:

This sould get the job done

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

CodePudding user response:

I think this should do the job:

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

CodePudding user response:

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>

  • Related