JavaScript: Number Constructor

By Xah Lee. Date: . Last updated: .
Number(arg)
Convert arg to a number Primitive Value , return it .
new Number(arg)
Convert arg to a number primitive value, return a number object that represent the number.
// Number called as function, return a number primitive value
console.log( ( typeof Number(3) ) === "number" ); // true
// Number called as constructor, returns a number object
console.log( ( typeof (new Number(3)) ) === "object" ); // true
console.log( Number(3) === (new Number(3)) ); // false

Convert to Number

Argument TypeResult
undefinedReturn NaN.
nullReturn +0.
true or falseReturn 1 if argument is true. Return +0 if argument is false.
NumberReturn argument (no conversion).
StringReturn a number or NaN.
SymbolThrow a TypeError exception.
ObjectReturn a number or NaN

Special literal values of number.

// test converting special literal value to number primitive.

// no change
console.log( Number( Infinity) === Infinity );
console.log( Number( -Infinity) === -Infinity );
console.log( Number.isNaN( Number( NaN) ) );

// changed
console.log( Number.isNaN( Number( undefined) ) );
console.log( Number( null) === 0 );
console.log( Number( true) === 1 );
console.log( Number( false) === 0 );
// all true

Convert string to number.

console.log( Number( "0.03") === 0.03 );

// extra zero before or after is ok
console.log( Number( "00.03") === 0.03 );
console.log( Number( "00.030") === 0.03 );

// extra space in front or back are ok
console.log( Number( "  0.03  ") === 0.03 );
console.log( Number( "  +0.03  ") === 0.03 );
console.log( Number( "  -0.03  ") === -0.03 );

// cannot have space after sign
console.log( Number.isNaN (Number( "- 0.03 ")) );

// cannot have space between digits
console.log( Number.isNaN( Number( "1 000"))  );

// all true

JavaScript Number

JS in Depth
XAH  BUY NOW

JS in Depth

JS Obj Ref

DOM


JS Obj Ref

Number

prototype