The Number Object
The Number object, since version 1.5 of JavaScript, features methods of conversion of numbers.
Using Number
A Number object is created by a call of the constructor with a numeric value in argument.
var n = new Number(numeric value);
Strings are valid arguments if they contain a numerical value.
var n = new Number("10000");
Hexadecimal numbers in the form 0xNNNN too.
var n = new Number(0xFF);
The numeric format of HTML is not recognized.
var n = new Number(#FF); // invalid
If the argument is not a number or is not directly convertible into number, the object will returns NaN, which means: Not A Number.
Attributes of the object
The Number object has attributes dedicated to testing the validity of its content:
MAX_VALUE: maximum value for the argument.
MIN_VALUE: minimum value.
NEGATIVE_INFINITY: buffer overflow obtained with a negative value too large.
POSITIVE_INFINITY: buffer overflow obtained with a positive value too large.
NaN: value of the object when a passed argument is invalid.
Do not use Number.NaN directly to test that, but rather use the isNaN function.
if( isNaN(new Number(x)) alert("Not a number");
Methods of Number
The essential methods are conversion functions. The methods can be applied to both a literal or the object:
alert(new Number(123).toString());
alert(123.toString());
var x = new Number(154.39);
alert(x.toFixed());
Methods:
toString: returns the object as a string. So 123 will be "123". If the argument was a string, this method returns the original value.
toFixed: returns the number in fixed-point notation. Without argument, returns the integer part.
var x = new Number(123.54)
x.toFixed() becomes 123
x.toFixed(1) becomes 123.5
toExponential: returns the value in exponential notation.
toPrecision: displays the value with the number of decimal digits given the argument of toPrecision. If there was no argument, the value is unchanged.
Number also inherits methods of Object.
Demonstration of the methods
The demo allows you to enter values in a text field, and to apply on them the methods of the Number object.