Random floating point double in Inclusive Range

后端 未结 13 681
感动是毒
感动是毒 2020-12-01 18:14

We can easily get random floating point numbers within a desired range [X,Y) (note that X is inclusive and Y is exclusive) with the function listed below since

13条回答
  •  暖寄归人
    2020-12-01 18:28

    Math.round() will help to include the bound value. If you have 0 <= value < 1 (1 is exclusive), then Math.round(value * 100) / 100 returns 0 <= value <= 1 (1 is inclusive). A note here is that the value now has only 2 digits in its decimal place. If you want 3 digits, try Math.round(value * 1000) / 1000 and so on. The following function has one more parameter, that is the number of digits in decimal place - I called as precision:

    function randomInRange(min, max, precision) {
        return Math.round(Math.random() * Math.pow(10, precision)) /
                Math.pow(10, precision) * (max - min) + min;
    }
    

提交回复
热议问题