Javascript Number Object








Number type is the reference type for numeric values.

To create a Number object, use the Number constructor and a number. Here's an example:

var numberObject = new Number(10);

Conversion

Number type overrides valueOf() to return the primitive numeric value represented by the object.

It has toLocaleString(), and toString() to return the number as a string.

The toString() method optionally accepts a single argument indicating the radix.


var num = 10;
console.log(num.toString());       //"10"
console.log(num.toString(2));      //"1010"
console.log(num.toString(8));      //"12"
console.log(num.toString(10));     //"10"
console.log(num.toString(16));     //"a"
console.log(num.valueOf());

The code above generates the following result.





Note

The typeof and instanceof operators work differently when dealing with primitive numbers versus reference numbers.


var numberObject = new Number(10);
var numberValue = 10;
console.log(typeof numberObject);   //"object"
console.log(typeof numberValue);    //"number"
console.log(numberObject instanceof Number);  //true
console.log(numberValue instanceof Number);   //false

Primitive numbers always return "number" when typeof is called on them, whereas Number objects return "object". Similarly, a Number object is an instance of Number, but a primitive number is not.

The code above generates the following result.





Number toFixed

toFixed() format a number with a specified number of decimal points.


var num = 10;
console.log(num.toFixed(2));    //"10.00"
num = 10.005;
console.log(num.toFixed(2));    //"10.01"

toFixed(2) formats number with two decimal places, filling out the empty decimal places with zeros. It also rounds the value.

The toFixed() method can represent numbers with 0 through 20 decimal places.

The code above generates the following result.

Number toExponential

toExponential() format number in exponential notation (e-notation).

toExponential() accepts the number of decimal places as parameter.


var num = 10;
console.log(num.toExponential(1));    //"1.0e+1"

The code above generates the following result.

Number toPrecision

toPrecision() returns either the fixed or the exponential representation of a number, depending on which makes the most sense.

This method takes one argument, which is the total number of digits to use to represent the number not including exponents.


var num = 99;
console.log(num.toPrecision(1));    //"1e+2"
console.log(num.toPrecision(2));    //"99"
console.log(num.toPrecision(3));    //"99.0"

The toPrecision() method can represent numbers with 1 through 21 decimal places.

The code above generates the following result.