The number data type is a primitive data type that can hold numeric values such as integers and floating-point numbers.
A number primitive can be declared using the literal notation:
var num_int = 42;
var num_float = 1.61803399;All numbers in JavaScript are 64-bit floating point numbers. JavaScript does not distinguish between integers and floating point numbers.
Integers can also be specified in octal (base 8) or hexadecimal (base 16) notation. To use the octal notation, numbers must be preceeded with a 0:
var num_oct = 052; // equivalent to 42 decimalTo use the hexadecimal notation, numbers must be preceeded with 0x:
var num_hex = 0x2a; // equivalent to 42 decimalThe JavaScript Number object represents a wrapper for the number primitive. A Number object can be created using the new Number() object constructor:
var num1 = new Number(value)The value parameter represents the numeric value of the object. For example, the following code will create a Number object with a value of 7:
var num2 = new Number(7);Calling the constructor without a parameter creates an object with an initial value of 0.
The global function Number() can be called without the new keyword to create a number primitive. For example:
var num3 = Number(3); // returns the primitive value 3
The Number() global function can also be used to explicitly convert a value to a number:
var num4 = Number("123");For a value that can not be converted to a number, the Number() function returns the special value NaN (Not-a-Number) which indicates that the expression could not be evaluated to a number. For example, converting arrays and objects to numbers is not possible, thus the function will return NaN:
Number([1, 2, 3]); // returns NaN
Only basic types such as strings and boolean values can be converted to numbers. Note, however, that a string can be converted to a number only if it is a numeric string:
Number("123"); // 123
Number("foo"); // NaN
Number("123foo"); // NaNconstructorNumber objectMAX_VALUEMIN_VALUENaNNaN is a special value indicating that the value is "Not-a-Number"NEGATIVE_INFINITYPOSITIVE_INFINITYprototypetoExponential([digits])Number object in exponential notation, also known as scientific notationtoFixed([digits])Number object formatted using fixed-point notationtoLocaleString()Number objecttoPrecision([precision])Number object to the specified precisiontoString([radix])Number object in the specified radix or basevalueOf()If you see a typo, want to make a suggestion or have anything in particular you'd like to know more about, please drop us an e-mail at hello at diveintojavascript dot com.
Copyright © 2010-2011 Dive Into JavaScript