Basic Usage

It is possible to make a Number object:

var x = new Number(3), y = new Number(4), z;
z = x + y;

But it is possible and usually preferable to do without making an object:

var a = 3, b = Number('4'), c;
c = a + b;

Usually the static properties are used directly:

if (a * b <= Number.MAX_VALUE) {
    funcA();
} else {
    funcB();
}

The Math global object and these global functions are also commonly used with numbers:

isFinite(NaN);
isNaN(NaN);
parseFloat('1.3');
parseInt('3');

Properties

The properties in ALL CAPS are static properties that are accessed directly from the prototype as opposed to an instance.

.constructor. See Object.contstuctor.

.MAX_VALUE. The largest number representable in JS, approximately 1.79E+308.

.MIN_VALUE. The smallest number representable in JS, approximately 5E-324.

.NaN. Special "Not a Number" value. The same as the top-level property NaN.

.NEGATIVE_INFINITY. Special value representing negative infinity; returned on overflow. The same as the top-level property Infinity.

.POSITIVE_INFINITY. Special value representing infinity; returned on overflow.

.prototype. Allows the addition of properties to a Number object.

Methods

.toExponential([fractionDigits]). Returns a string representing the number in exponential notation.

.toFixed([digits]). Returns a string representing the number with the specified number of digits after the decimal point. Defaults to no digits.

.toLocaleString(). Returns a string representing the nuber is a human readable format.

.toPrecision([digits]). Returns a string representing the number in fixed or exponential notation for the specified number of significant digits.

.toSource(). Returns an object literal representing the specified Number object; you can use this value to create a new object. Overrides the Object.toSource() method.

.toString(). Returns a String representing the specified object. Overrides the Object.toString() method.

.valueOf(). Returns the primitive value of the specified object. Overrides the Object.valueOf() method.

Miscellany

Miscellaneous notes pertaining to numbers in JavaScript as well as the Number object.

There are two kinds of number literals in JavaScript:

  • Integer
    • Decimal integers have no leading 0 (zero). EGs: -1, -0, 0, +0, 1.
    • Octal integers have a leading 0. EGs: -07, 00, 002, 066.
    • Hexadecimal integers start with 0x or 0X. EGs: -0xA, 0x0, 0xF9.
  • Floating-Point, with this syntax: [(+|-)][digits][.digits][(E|e)[(+|-)]digits]
    • 0.8
    • -0.8e7
    • 98E-76

For evaluating expressions as numbers in JS: Literal numbers have the value stated, but others depend on context.

  • undefined get treated as NaN.
  • null get treated as 0.
  • Empty strings can be 0 (EG: Number("")) or can auto type-convert its neighbors to Strings (EG: 8+""+8 yields 88 not 16).
  • false gets treated as 0.
  • true gets treated as 1.


GeorgeHernandez.comSome rights reserved