Java Reference
In-Depth Information
var diceThrow;
for (var throwCount = 0; throwCount < 10; throwCount++) {
diceThrow = (Math.floor(Math.random() * 6) + 1);
document.write(diceThrow + "<br>");
}
</script>
</body>
</html>
You want
diceThrow
to be between
1
and
6
. The
random()
function returns a floating‐point number
between
0
and just under
1
. By multiplying this number by
6
, you get a number between
0
and just under
6
. Then by adding
1
, you get a number between
1
and just under
7
. By using
floor()
to always round it
down to the next lowest whole number, you can ensure that you'll end up with a number between
1
and
6
.
If you wanted a random number between
1
and
100
, you would just change the code so that
Math.random()
is multiplied by 100 rather than 6.
the pow() Method
The
pow()
method raises a number to a specified power. It takes two parameters, the first being the
number you want raised to a power, and the second being the power itself. For example, to raise 2 to
the power of 8 (that is, to calculate 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2), you would write
Math.pow(2,8)
—
the result being
256
. Unlike some of the other mathematical methods, like
sin()
,
cos()
, and
acos()
,
which are not commonly used in web programming unless it's a scientific application you're writing,
the
pow()
method can often prove very useful.
trY it out
Using pow()
In this example, you write a function using
pow()
, which fixes the number of decimal places in a number:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter <5, Example 5</title>
</head>
<body>
<script>
function fix(fixNumber, decimalPlaces) {
var div = Math.pow(10, decimalPlaces);
fixNumber = Math.round(fixNumber * div) / div;
return fixNumber;
}
var number1 = prompt("Enter the number with decimal places you " +
"want to fix", "");
var number2 = prompt("How many decimal places do you want?", "");
document.write(number1 + " fixed to " + number2 + " decimal places is: ");
document.write(fix(number1, number2));