HTML and CSS Reference
In-Depth Information
EXAMPLE
9.21
<html>
<head><title>The Math Object</title></head>
<body>
<h2>Rounding Numbers</h2>
<p>
<h3>
<script type="text/javascript">
1
var num=16.3;
document.write("<I>The number being manipulated is: ", num,
"</I><br /><br />");
2
document.write("The <I>Math.floor</I> method rounds down: "
+
Math.floor(num)
+ "<br />");
3
document.write("The <I>Math.ceil</I> method rounds up: " +
Math.ceil(num)
+"<br />");
4
document.write("The <I>Math.round</I> method rounds to\
the nearest integer: " +
Math.round(num)
+ "<br />");
</script>
</h3>
</body>
</html>
EXPLANATION
1
The number 16.3 will be manipulated by the
Math
object's methods.
2
The
Math
object's
floor()
method rounds the number down to the next lowest
whole number. 16.3 rounds down to 16.
3
The
Math
object's
ceil()
method rounds a number up. 16.3 becomes 17.
4
The
Math
object's
round()
methods round 16.3 up only if the decimal part of the
number is 5 or higher (see Figure 9.25).
Figure 9.25
Output from Example 9.21.
Random numbers are frequently used in JavaScript programs to produce random images
(such as banners streaming across a screen), random messages, or random numbers