Generate random number between two numbers in JavaScript

后端 未结 23 2047
走了就别回头了
走了就别回头了 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:38

    Adding float with fixed precision version based on the int version in @Francisc's answer:

    function randomFloatFromInterval (min, max, fractionDigits) {
      const fractionMultiplier = Math.pow(10, fractionDigits)
      return Math.round(
        (Math.random() * (max - min) + min) * fractionMultiplier,
      ) / fractionMultiplier
    }
    

    so:

    randomFloatFromInterval(1,3,4) // => 2.2679, 1.509, 1.8863, 2.9741, ...
    

    and for int answer

    randomFloatFromInterval(1,3,0) // => 1, 2, 3
    
    0 讨论(0)
  • 2020-11-22 01:39

    Try using:

    function random(min, max) {
       return Math.round((Math.random() *( Math.abs(max - min))) + min);
    }
    console.log(random(1, 6));

    0 讨论(0)
  • 2020-11-22 01:40

    jsfiddle: https://jsfiddle.net/cyGwf/477/

    Random Integer: to get a random integer between min and max, use the following code

    function getRandomInteger(min, max) {
      min = Math.ceil(min);
      max = Math.floor(max);
      return Math.floor(Math.random() * (max - min)) + min;
    }
    

    Random Floating Point Number: to get a random floating point number between min and max, use the following code

    function getRandomFloat(min, max) {
      return Math.random() * (max - min) + min;
    }
    

    Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

    0 讨论(0)
  • 2020-11-22 01:40

    Example

    Return a random number between 1 and 10:

    Math.floor((Math.random() * 10) + 1);
    

    The result could be: 3

    Try yourself: here

    --

    or using lodash / undescore:

    _.random(min, max)

    Docs: - lodash - undescore

    0 讨论(0)
  • 2020-11-22 01:41

    This should work:

    const getRandomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min
    
    0 讨论(0)
  • 2020-11-22 01:41

    This function can generate a random integer number between (and including) min and max numbers:

    function randomNumber(min, max) {
      if (min > max) {
        let temp = max;
        max = min;
        min = temp;
      }
    
      if (min <= 0) {
        return Math.floor(Math.random() * (max + Math.abs(min) + 1)) + min;
      } else {
        return Math.floor(Math.random() * max) + min;
      }
    }
    

    Example:

    randomNumber(-2, 3); // can be -2, -1, 0, 1, 2 and 3
    randomNumber(-5, -2); // can be -5, -4, -3 and -2
    randomNumber(0, 4); // can be 0, 1, 2, 3 and 4
    randomNumber(4, 0); // can be 0, 1, 2, 3 and 4
    
    0 讨论(0)
提交回复
热议问题