[Prev: Function type] [Home] [Next: Object]
A Number is a datatype that represents a number. In most situtations, programmers will use numeric literals like 3.142 directly in code. The Number datatype is useful for obtaining system limits, e.g. MIN_VALUE and MAX_VALUE, and for performing number to string conversions with toExponential(), toFixed(), toPrecision() and toString().
Numbers are not normally constructed, but instead created by simple assignment, e.g.
var x = 3.142;
System.println( Number.MAX_VALUE ); System.println( Number.MIN_VALUE );
The maximum and minimum values are floating point values.
A numeric variable may hold a non-numeric value, in which case isNaN() returns true. The result of an arithmetic expression may exceed the maximum or minimum representable values in which case the value of the expression will be Infinity, and isFinite() will return false.
toExponential( optDecimals )
var x = 999.8765; System.println( x.toExponential() ); // Prints: 9.998765e+1 System.println( x.toExponential( 1 ) ); // Prints: 9.9e+1
This function returns a string representation of the number using scientific (exponential) notation. If optDecimals is given, it specifies the number of decimal places to use in the resultant string.
toFixed( optDecimals )
var x = 999.8765; System.println( x.toFixed() ); // Prints: 999 System.println( x.toFixed( 1 ) ); // Prints: 999.9
This function returns a string representation of the number using a fixed number of decimal places. The default number of places is zero; the number of decimal places to use may be given as optDecimals. The number is rounded if necessary.
toPrecision( optSignificanDigits )
var x = 999.8765; System.println( x.toPrecision() ); // Prints: 999.8765 System.println( x.toPrecision( 1 ) ); // Prints: 999.9
This function returns a string representation of the number using a fixed number of decimal places or using scientific notation. By default all digits are used, but by specifying the number of significant digits (optSignificanDigits) to be less than the number available, rounding will occur.
toString()
var x = 999.8765; System.println( x.toString() ); // Prints: 999.8765
This function returns a string representation of the number. It is the same as using toPrecision() with no argument.