Using the JS Math.random () function to generate random digital _javascript techniques between N and M

Source: Internet
Author: User

Summary:

This article explains how to use JS to generate a random number between m, the main purpose is for the later JS generated verification code to prepare.

The Math.random () function returns a pseudo-random number between 0 and 1, possibly 0, but always less than 1,[0,1

Generates an integer that contains n but does not contain m: n-m

The first step is to calculate the value of the m-n, assuming equal to W

Step two math.random () *w

Step three math.random () *w+n

Fourth Step parseint (Math.random () *w+n, 10)

Generates N-M, not containing n but an integer containing M:

The first step is to calculate the value of the m-n, assuming equal to W

Step two math.random () *w

Step three math.random () *w+n

Fourth Step Math.floor (Math.random () *w+n) + 1

Generates N-M, no integers containing N and m:

The first step is to calculate the value of the m-n-2, assuming equal to W

Step two math.random () *w

Step three math.random () *w+n +1

Fourth Step Math.Round (Math.random () *w+n+1) or Math.ceil (Math.random () *w+n+1)

Generates N-M, containing the random number of N and M:

The first step is to calculate the value of the m-n, assuming equal to W

Step two math.random () *w

Step three math.random () *w+n

Fourth Step Math.Round (Math.random () *w+n) or Math.ceil (Math.random () *w+n)

Example:

Generates a random integer of 800-1500 that contains 800 but does not contain 1500

Copy Code code as follows:

1500-800 = 700
Math.random () *700
var num = math.random () *700 + 800;
num = parseint (num, 10);

It only takes a simple four steps to complete.

Add:

Math.ceil () returns the smallest integer (rounded function) greater than or equal to the numeric argument, rounding the number

Math.floor () returns the largest integer less than or equal to a numeric parameter, rounding the number

Math.Round () returns the nearest integer to the number, rounded

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.