.toPrecision()

The .toPrecision() method converts a number to a string of its specificied 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?

Code
Output
Loading...

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.

Learn JavaScript on Codecademy

Contributors