A method for calculating random numbers between arbitrary values in JS

Source: Internet
Author: User

This article mainly introduces the method that JS calculates random number between arbitrary value, analyzes the use skill of math.random function, has certain reference value, the friend who needs can refer to

This paper illustrates the method of calculating random number between arbitrary values by JS. Share to everyone for your reference. The implementation methods are as follows:

First: The Math.random () method is to compute random numbers that return greater than or equal to 0 less than 1.

Math.random () *10 not return is greater than or equal to 0 return less than 10, but he can only return less than 10 of the number, can not return 10, how to do, we add 1 on the original function into the math.random () *10+1; You can return a random number from 1 to 10 at this point, but we're returning a lot of decimals, not meeting the requirements, and we're using the Math.floor () function, which performs rounding down, That is to say 10.99 after Math.floor are 10,math.ceil (rounded up) even if 10.00001, return is 11, now we are finding the result:

The code is as follows: Math.floor (Math.random () *10+1); So we can find the result.

What about the 2 to 10 function, directly on the code

The code is as follows: Math.floor (Math.random () *9+2);

That 3 to 11, 4 to 88, each time such a calculation is not a way, the following to introduce a common method;

The code is as follows: function Selectfrom (lowvalue,highvalue) {
var choice=highvalue-lowvalue+1;
Return Math.floor (Math.random () *choice+lowvalue);
}

And then directly adjust the above method ok

I hope this article will help you with your JavaScript programming.

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.