JavaScript .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.1415console.log(pi.toPrecision(3)); // Output: 3.14console.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?
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
- Includes 34 Courses
- With Professional Certification
- Beginner Friendly.115 hours
- Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
- Beginner Friendly.15 hours