2

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.
DarkBee
  • 16,592
  • 6
  • 46
  • 58
Ben
  • 31
  • 6
  • 2
    https://stackoverflow.com/questions/11022488/javascript-using-round-to-the-nearest-10/11022517 – ptts Feb 09 '22 at 08:27
  • Does this answer your question? [Javascript using round to the nearest 10](https://stackoverflow.com/questions/11022488/javascript-using-round-to-the-nearest-10) – flololan Feb 09 '22 at 08:31
  • 2
    Just generate random integer in **smaller range** and multiply by 10 – MBo Feb 09 '22 at 08:45

3 Answers3

1

I think this should do the job:

result = Math.round((Math.floor(Math.random() * max) + min) / 10) * 10;
Sven
  • 66
  • 4
0

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>
0

This sould get the job done

 Math.round((Math.floor(Math.random() * max) + min) / 10) * 10
Shatsuki
  • 50
  • 3
  • 19