JavaScript Tutorial





Español Français 中文 Deutsch Portuguese Japanese nederlands
   
 
Java-Script Tutorial
Introduction Introduction
Variables Variables
Operators Operators
Statements Statements
Loops Loops
Functions Functions
Objects Objects
Arrays Arrays
Cookies JS Cookies
Browser Objects Browser Objects
Form DOM Form DOM
Style Objects DOM Style Objects
Forums Ask Your Doubts
Scraps More about Javascript
Feedback Feedback
 




Math Random Numbers


Tutorials Javascript

Topic

how to create a random number in javascript?
or
how to create a random number between two numbers e.g: 0 and 1000 in javascript?



Explanation

Object: Math

Method: Random

      Math.random() will create a decimal number between 0 and 1 (e.g: 0.833556767). We have to use the following procedure to convert the decimal number to a random number of use.

Creating a random number less than a value:
       To create a random number less than any value, we will have to use two functions, random and round of Math object. For an example we will try to create a random number less than 1000

Example:
<script language=javascript>
var xx = Math.random();
var rnumber = Math.round(xx*1000);
document.write(rnumber);
</script>

Result:

In the above example,
  • First a random decimal number was created using Math.random()
  • Now we multiply it with the number below which we want random number to be.
  • Pass is as the argumnet to Math.Round to remove the decimal points.
  • If we would want a number below 100, we would have to use 100 instead of 1000.






  • A Note
    Javascript (JS) is one of the most used languages in the world. Some times spelled as Java Script. Hope you enjoy this tutorial. Do send your feedback or suggestions on this javascript or java script tutorial. This is a copyright content.

    Other Links

    web hosting