.toPrecision()

Published Aug 23, 2021Updated Oct 8, 2022
Contribute to Docs

The .toPrecision() method converts a number to a string of its specified precision form.

Syntax

num.toPrecision(precision);
  • precision (optional): The number of significant digits.

Examples

Converting number to a string:

const pi = 3.14159;
console.log(pi.toPrecision(5)); // Output: 3.1415
console.log(pi.toPrecision(3)); // Output: 3.14
console.log(pi.toPrecision(1)); // Output: 3

To verify if it is a string:

const pi = 3.14159;
console.log(typeof pi.toPrecision());
// Output: string

Codebyte Example

Before running the program, what do you think the result will be?

us
Visit us
code
Hide code
Code
Output
Hide output
Hide output
Loading...

All contributors

Looking to contribute?

Learn JavaScript on Codecademy