Javascript - Number Number format


The toFixed() method returns a string representation of a number with a specified number of decimal points:

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

In the code above toFixed() method is given an argument of 2, which indicates two decimal places should be displayed.

If the number has more than the given number of decimal places, the result is rounded to the nearest decimal place:

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

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


toExponential() method returns a string with the number formatted in exponential notation.

toExponential() accepts one argument, which is the number of decimal places to output.

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

This code outputs "1.0e+1" as the result.


The toPrecision() method 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"

In this example, the first task is to represent the number 99 with a single digit, which results in "1e+2" or 100.

Because 99 cannot accurately be represented by just one digit, the method rounded up to 100, which can be represented using just one digit.

Representing 99 with two digits yields "99" and with three digits returns "99.0".

The toPrecision() method determines whether to call toFixed() or toExponential() based on the numeric value.

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

The Number object gives functionality to numeric values.

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 return "number" when used with typeof, whereas Number objects return "object".