What is toPrecision() in Javascript?

toPrecision() is a Number method that is used to format a number to a specific precision. In other words, the toPrecision() method formats a number to a given length by either rounding off to reduce the length or adding zeros to increase the length.

Declaration

The toPrecision() method is declared as follows:

num.toPrecision(len)
  • num: The number to be formatted to the precision len.
  • len: The precision in which num will be formatted; len is an optional parameter.

Note:

  • If len is not passed as a parameter, the toPrecision() method simply converts num to a string.
  • len must be in the range 1 to 100. Otherwise, RangeError is thrown.

Return value

The toPrecision() method returns a string that represents the number num in precision len.

Browser compatibility

The toPrecision() method is supported by the following browsers:

  • Edge 12
  • Firefox 1
  • Google Chrome 1
  • Internet Explorer 5.5
  • Opera 7
  • Safari 2

Example

Consider the code snippet below, which demonstrates the use of the toPrecision() method:

var num = 15.199
console.log("15.199 to precision of no length is: ",num.toPrecision());
console.log("15.199 to precision of length 3 is: ",num.toPrecision(3));
console.log("15.199 to precision of length 7 is: ",num.toPrecision(7));

Explanation

A number num is initialized with num = 15.199 in line 1.

  • line 3: The toPrecision() method is not passed the input parameter, so num is simply converted to a string.
  • line 5: num is converted to the precision of length = 3 by rounding off num to make it of length = 3.
  • line 7: num is converted to the precision of length = 7 by adding zeros to the right of num to make it of length = 7.

Free Resources

Copyright ©2026 Educative, Inc. All rights reserved