Javascript - Number toPrecision() Method

The toPrecision() method formats a number to a specified length.

Description

The toPrecision() method formats a number to a specified length.

A decimal point and nulls are added (if needed), to create the specified length.

Syntax

number.toPrecision(x)

Parameter Values

Parameter Require Description
x Optional.The number of digits. If omitted, it returns the entire number without any formatting

Return

A String, representing a number formatted to the specified precision

Example

Format a number into a specified length:

Demo

//display the formatted number.
var num = 13.5678;
console.log(num.toPrecision(2));//from w ww .  j  ava2 s.com

//Format a number to a specified length:
var num = 13.56789;
var a = num.toPrecision();
var b = num.toPrecision(2);
var c = num.toPrecision(3);
var d = num.toPrecision(10);

var n = a + "\n" + b + "\n" + c + "\n" + d;

console.log(n);

//Format a number between 0 and 1:

var num = 0.0016789;
var a = num.toPrecision();
var b = num.toPrecision(2);
var c = num.toPrecision(3);
var d = num.toPrecision(10);

var n = a + "\n" + b + "\n" + c + "\n" + d;

console.log(n);

Result