Generate random number between two numbers in JavaScript

后端 未结 23 2061
走了就别回头了
走了就别回头了 2020-11-22 01:09

Is there a way to generate a random number in a specified range (e.g. from 1 to 6: 1, 2, 3, 4, 5, or 6) in JavaScript?

23条回答
  •  别跟我提以往
    2020-11-22 01:47

    Inspite of many answers and almost same result. I would like to add my answer and explain its working. Because it is important to understand its working rather than copy pasting one line code. Generating random numbers is nothing but simple maths.

    CODE:

    function getR(lower, upper) {
    
      var percent = (Math.random() * 100);
      // this will return number between 0-99 because Math.random returns decimal number from 0-0.9929292 something like that
      //now you have a percentage, use it find out the number between your INTERVAL :upper-lower 
      var num = ((percent * (upper - lower) / 100));
      //num will now have a number that falls in your INTERVAL simple maths
      num += lower;
      //add lower to make it fall in your INTERVAL
      //but num is still in decimal
      //use Math.floor>downward to its nearest integer you won't get upper value ever
      //use Math.ceil>upward to its nearest integer upper value is possible
      //Math.round>to its nearest integer 2.4>2 2.5>3   both lower and upper value possible
      console.log(Math.floor(num), Math.ceil(num), Math.round(num));
    }
    

提交回复
热议问题