Section 4.2. The Number Object


4.2. The Number Object

The Number object's unique methods have to do with conversionto 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.

Figure 4-1. The Number object methods


In Example 4-1, two numeric constantsMAX_VALUE and MIN_VALUEreflect 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 pointin 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 decimalrounded if applicable. A method not included in the demonstration is toLocaleString, which prints out the number formatted for a given locale.




Learning JavaScript
Learning JavaScript, 2nd Edition
ISBN: 0596521871
EAN: 2147483647
Year: 2006
Pages: 151

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net