The Number Object

The Number object’s unique methods have to do with conversion—to string, to locale-specific string, to a given precision- or fixed-point representation, and to exponential notation. The object also has four constant numeric properties, directly accessible from the Number object.

Rather than list each Number object’s methods and properties, Example 4-1 demonstrates how they work by calling each and printing out their results and/or values.

Example 4-1. The Number object methods

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>The Number Object</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<script type="text/javascript">
//<![CDATA[

// Number properties
document.writeln(Number.MAX_VALUE + "<br />");
document.writeln(Number.MIN_VALUE + "<br />");
document.writeln(Number.NEGATIVE_INFINITY + "<br />");
document.writeln(Number.POSITIVE_INFINITY + "<br />");

// Number specific methods
var newValue = new Number("34.8896");

document.writeln(newValue.toExponential(3) + "<br />");
document.writeln(newValue.toPrecision(3) + "<br />");
document.writeln(newValue.toFixed(6) + "<br />");


//]]>
</script>
</body>
</html>

Figure 4-1 shows the results of running this JavaScript application.

The Number object methods

Figure 4-1. The Number object methods

In Example 4-1, two numeric constants—MAX_VALUE and MIN_VALUE—reflect the maximum and minimum numbers that can be represented in JavaScript. The other two infinity values represent specialized negative and positive infinity, returned when a math overflow happens or the minimum or maximum numbers are exceeded. In Chapter 2, we looked at the Infinity global constant in the section “The Number Data Type”; POSITIVE_INFINITY is equivalent to this value.

After printing out the numeric constants, the program creates an instance of a Number object. Either a string or a number can be used for the literal value, as long as the format is a proper number. If a string is used without a proper number, the value of the object is NaN.

The first method invoked is toExponential, which passes in the number of digits appearing after the decimal point—in this case, 3. The second method is toPrecision, which passes in a value of 3 also, representing the number of significant digits to include in the string transformation. The last method called, toFixed, is the number of digits to print out after the decimal—rounded if applicable. A method not included in the demonstration is toLocaleString, which prints out the number formatted for a given locale.

Get Learning JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.