HTML and CSS Reference
In-Depth Information
Figure 9.36 Constants, number conversion, and NaN : Output from Example 9.31.
Formatting Numbers. To convert floating-point numbers to a string with a speci-
fied number of significant digits, JavaScript provides the toFixed() and toExponential()
methods. You can apply these methods to a numeric variable whether it is created as
a numeric literal or as an object.
EXAMPLE 9.32
<html>
<head><title>Number Object</title></head>
<body bgcolor="orange">
<font color="black" size="+1">
<h2>Formatting Numbers</h2>
<script type="text/javascript">
1
var n = new Number(22.425456);
// var n = 22.425456;
2
document.write("<b>The unformatted number is " + n
+ "<br />");
3
document.write("The formatted number is "+ n.toFixed(2) +
"<br />");
4
document.write("The formatted number is "+ n.toFixed(3) +
"</b><br />");
</script>
</font>
</body>
</html>
EXPLANATION
1
A new Number object is created and assigned to the variable n . It is a wrapper for
the primitive number.
2
The value of the number is displayed as a large floating-point number, 22.425456.
3
The Number object's toFixed() method gets an argument of 2. This fixes the deci-
mal point two places to the right and rounds up if necessary. The new value is
22.43.
4
This time the toFixed() method will format the number with three numbers to the
right of the decimal point (see Figure 9.37).
 
Search WWH ::




Custom Search