JavaScript Number toPrecision()

The syntax of the toPrecision() method is:

num.toPrecision(precision)

Here, num is a number.


Number toPrecision() Parameters

The toPrecision() method takes in:

  • precision (Optional) - An integer specifying the number of significant digits

Notes:

  • If precision is omitted, it behaves as Number.toString() and the entire number is returned.
  • If precision is a non-integer value, it is rounded to the nearest integer.

Return value from Number toPrecision()

  • Returns a String, representing a number rounded to precision significant digits.

Note: The toPrecision() method throws a RangeError if precision is not in between 1 and 100.


Example: Using Number.toPrecision()

let num = 57.77583;

console.log(num.toPrecision()); // 57.77583 -> similar to toString()
console.log(num.toPrecision(5)); // 57.776
console.log(num.toPrecision(2)); // 58
console.log(num.toPrecision(1)); // 6e+1 -> in somecases, exponential notation

num = 0.000123;
console.log(num.toPrecision()); // 0.000123
console.log(num.toPrecision(5)); // 0.00012300
console.log(num.toPrecision(2)); // 0.00012
console.log(num.toPrecision(1)); // 0.0001

Output

57.77583
57.776
58
6e+1
0.000123
0.00012300
0.00012
0.0001

Recommended Readings:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges