


Use js Math.random() function to generate random numbers between n and m_javascript skills
May 16, 2016 pm 04:34 PMSummary:
This article explains how to use js to generate random numbers between n and m. The main purpose is to prepare for the later js generation of verification codes.
Math.random() function returns a pseudo-random number between 0 and 1, which may be 0 but is always less than 1, [0,1)
Generate n-m, integers including n but not m:
The first step is to calculate the value of m-n, assuming it is equal to w
The second step Math.random()*w
Step 3 Math.random()*w n
Step 4 parseInt(Math.random()*w n, 10)
Generate n-m, an integer that does not contain n but contains m:
The first step is to calculate the value of m-n, assuming it is equal to w
The second step Math.random()*w
Step 3 Math.random()*w n
Step 4 Math.floor(Math.random()*w n) 1
Generate n-m, an integer excluding n and m:
The first step is to calculate the value of m-n-2, assuming it is equal to w
The second step Math.random()*w
Step 3 Math.random()*w n 1
Step 4 Math.round(Math.random()*w n 1) or Math.ceil(Math.random()*w n 1)
Generate n-m, random numbers containing n and m:
The first step is to calculate the value of m-n, assuming it is equal to w
The second step Math.random()*w
Step 3 Math.random()*w n
Step 4 Math.round(Math.random()*w n) or Math.ceil(Math.random()*w n)
Example:
Generate a random integer between 800-1500, including 800 but not including 1500
1500-800 = 700
Math.random()*700
var num = Math.random()*700 800;
num = parseInt(num, 10);
It only takes four simple steps to complete.
Supplement:
Math.ceil() returns the smallest integer (rounding function) that is greater than or equal to the numeric parameter, and rounds the number up
Math.floor() returns the largest integer less than or equal to the numeric parameter, rounding the number down
Math.round() returns the number to the nearest integer, rounded

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Calculate the natural logarithm using Java's Math.log() function

How to generate a non-repeating random 4-digit number using php

How to use demo of python random library

Java generates random double precision floating point numbers using nextDouble() function of Random class

Use the math.Log2 function to calculate the base 2 logarithm of a specified number

Python's Math library: usage and introduction to common functions

How to solve the problem of generating the same random numbers using php rand function

How to use the random.choice() function to randomly select an element from a list in Python 2.x
