Java Reference
In-Depth Information
diceThrow = (Math.floor(Math.random() * 6) + 1);
document.write(diceThrow + “<br>”);
}
</script>
</body>
</html>
You wa nt
diceThrow
to be between
1
and
6
. The
random()
function returns a fl oating-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 specifi ed power. It takes two parameters, the fi rst 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 scientifi c application you're writing, the
pow()
method can often prove very useful.
Try It Out Using pow()
In the following example, you write a function using
pow()
, which fi xes the number of decimal places
in a number — a function that's missing from earlier versions of JavaScript, though it has now been
added to JScript 5.5 and JavaScript 1.5, as you'll see later in this chapter. This helps demonstrate that
even when a function is missing from JavaScript, you can usually use existing functions to create what
you want.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title>Chapter 5: Example 5</title>
</head>
<head>
<script type=”text/javascript”>
function fix(fixNumber, decimalPlaces)
{
var div = Math.pow(10,decimalPlaces);
fixNumber = Math.round(fixNumber * div) / div;
return fixNumber;
}
</script>
</head>
<body>