1. Randomly take an int range of one number, such as 0-3 to take 0,1,2,3, including 0 and 3
<script> var rand = {};rand.getint = function (begin,end) {return Math.floor (Math.random () * (End-begin + 1)) + be gin;} var v = rand.getint (0,3) alert (v);</script>
Common error notation:
<script> var rand = {};rand.getint = function (begin,end) {return Math.floor (Math.random () * (end-begin)) + Begin;} var v = rand.getint (0,3) alert (v);</script>
because the range of Javascirpt math.random () is [0,1], contains 0, does not contain 1, the error is written, because Math.floor is rounded down, so:
The value range of Math.floor ([0,1) * 3) + 0 is [0,1,2] and will never be 3.
2. Random fetch float range one number
<script> var rand = {};rand.get = function (begin,end,precision) {return (Math.random () * (End-begin) + begin). ToFixed (precision);} var v = rand.get (0,3,2) alert (v);</script>
It is a problem to take less than 3, and there is no good way to do it.
http://www.waitingfy.com/archives/1760
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Javascript random number int range one number float