JavaScript gets any random number between two numbers

Source: Internet
Author: User

Sweep and reward support Q Group communication651176910Shared thePeople support!!!

With JavaScript's math.random () method, you can get random numbers from 0 to 1, so how do you get the number randomly between any given two numbers? such as obtaining a random number between 2 and 5, a random number between 5 and 10, etc.

Since the math.random () function always returns a random number from 0 to 1, we can think of 0 as the minimum number and 1 as the maximum number. Assuming that the minimum number is Max and the maximum number is min, we can draw a random number between any two numbers using the following formula:

Math.random () * (max-min) + min

If you use Math.floor () for a down-rounding operation, you need to Max-min + 1, which is:

Math.floor (Math.random () * (max-min) + min)

If you want to specify the number of decimal digits, you can use the math.round () function. As the following formula returns a random number between any two integers, the result retains 1 decimal places:

Math.Round ((Math.random () * (max-min) + min) * 10)/10

JavaScript gets any random number between two numbers

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.