Javascript random number int range one number float

Source: Internet
Author: User
Tags float range

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.