Java Reference
In-Depth Information
Then you write out the number and some descriptive text.
document.write(“<h3>The number you entered was “ + myNumber + “</h3><br />”);
document.write(“<p>The rounding results for this number are</p>”);
Notice how this time some HTML tags for formatting have been included — the main header being in
<h3>
tags, and the description of what the table means being inside a paragraph
<p>
tag.
Next you create the table of results.
document.write(“<table width=150 border=1>”);
document.write(“<tr><th>Method</th><th>Result</th></tr>”);
document.write(“<tr><td>parseInt()</td><td>”+ parseInt(myNumber) +”</td></tr>”);
document.write(“<tr><td>ceil()</td><td>” + Math.ceil(myNumber) + “</td></tr>”);
document.write(“<tr><td>floor()</td><td>”+ Math.floor(myNumber) + “</td></tr>”);
document.write(“<tr><td>round()</td><td>” + Math.round(myNumber) +”</td></tr>”);
document.write(“</table>”)
You create the table header fi rst before actually displaying the results of each rounding function on a
separate row. You can see how easy it is to dynamically create HTML inside the web page using just
JavaScript. The principles are the same as with HTML in a page: You must make sure your tag's syntax
is valid or otherwise things will appear strange or not appear at all.
Each row follows the same principle but uses a different rounding function. Let's look at the fi rst row,
which displays the results of parseInt().
document.write(“<tr><td>parseInt()</td><td>”+ parseInt(myNumber) +”</td></tr>”);
Inside the string to be written out to the page, you start by creating the table row with the
<tr>
tag.
Then you create a table cell with a
<td>
tag and insert the name of the method from which the results
are being displayed on this row. Then you close the cell with
</td>
and open a new one with
<td>
.
Inside this next cell you are placing the actual results of the
parseInt()
function. Although a number
is returned by
parseInt()
, because you are concatenating it to a string, JavaScript automatically con-
verts the number returned by
parseInt()
into a string before concatenating. All this happens in the
background without you needing to do a thing. Finally, you close the cell and the row with
</td></tr>
.
The random() Method
The
random()
method returns a random fl oating-point number in the range between
0
and
1
, where
0
is included and
1
is not. This can be very useful for displaying random banner images or for writing a
JavaScript game.
Let's look at how you would mimic the roll of a single die. In the following page, 10 random numbers
are written to the page. Click the browser's Refresh button to get another set of random numbers.
<html>
<body>
<script type=”text/javascript”>
var throwCount;
var diceThrow;
for (throwCount = 0; throwCount < 10; throwCount++)
{