Generate random number between two numbers in JavaScript

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

提交回复
热议问题