How can I create a random number using JavaScript? I am thinking of building a script that will utilize a random number and need it to be done with JavaScript.
The use of random numbers in JavaScript is something that is very popular for various goals.
Basic JavaScript Random Number
=-=-=-=-=-=-=-=-=-=-==-=-=-=-=
To create your random number you can use the following JavaScript code:
<script language="JavaScript">
var random_no = Math.random();
document.write(random_no);
</script>
This will produce a random number between 0 and 1.
Setting the number of random options
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
To set a range starting at 0 and including 0 you would multiplying it by X where X is the number of possible results. In my example X is 10.
By adding Math.round we remove all decimal options from being included.
<script language="JavaScript">
var random_no = Math.round(Math.random()*10);
document.write(random_no);
</script>
This will produce a number that could be anything from 0 - 9.
Setting the starting point of a random number
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
To set the starting point of a range we simply add that number.
Eg adding 1 in the code below makes the range begin at 1 since 0+1=1.
<script language="JavaScript">
var random_no = (Math.round(Math.random()*10)+1);
document.write(random_no);
</script>