Javascript

JavaScript Random Number Generator.

JavaScript Random Number Generator
Written by Saiful Islam

JavaScript is a client side script language and most popular among scripting language. It is very powerful language. It has a build in Math library that can do mathematical calculation powerfully. Now I describe about the strategy of using JavaScript Random Number Generator. I hope you already have basic knowledge about JavaScript Math library, so I switch only on random number.

JavaScript Random Number Generator :

JavaScript Math library has a function random() that generates a random number from 0 to 1. But actually it is not a real number. You may tell it is a pseudorandom number, because this function uses a very complex algorithm to generate a number which is very near to random number for practical purpose.

The main syntax for random number generation:

Here, the random() function only returns a number between o and 1, but you may need to get a random number between 0 to x where x is an integer number. In this situation you need to multiply x with the random() function.

Syntax:

Example:

This example will return a number between 0 and 10. But if you want an integer number as output then you need to round up that number. In this situation floor() function gives you relief from floating number problem. The floor() function returns the output number as downwards rounded.

Syntax:

Example:

From this example you will get a rounded or an integer random number. Yet you are not able to get a javascript random number generator from negative to positive number or y to x number where x and y are two integer number and not equal to 0. There is no direct function to execute it. So here are the main tips for you. Now I use a mathematical equation for find out a random number between any numbers or any ranges.

Suppose, you go to find out a random number between -12 to 12 then just add the -12 with the random() function and also multiply 12+12+1 with this function. Because adding -12 gives you the minimum range and multiplying 12+12+1 gives you the maximum range. Here the common function for this calculation:

This function receives two numbers which indicate the range and return a random number between that ranges.

Example:

This function will return a random number between 5 and 17.

 

Here a complete JavaScript code to get a random number between any ranges:

Output:

 

About the author

Saiful Islam

2 Comments

Leave a Comment