How to use toPrecision() Method In Javascript
The number of total digits in float values can be set using the toPrecision() method. This method converts the number into a string, keeping the total number of digits of the value as specified and rounding them to the nearest number. If no value is passed as a parameter, then the function acts as a toString() function effectively returning the value passed as a string.
Syntax:
number.toPrecision(precision);
Example: This example shows the use of the toPrecision() method.
Javascript
pi = 3.14159265359; twoPlaces = pi.toPrecision(2); fivePlaces = pi.toPrecision(5); console.log(twoPlaces); console.log(fivePlaces); |
Output
3.1 3.1416
Floating point number precision in JavaScript
The representation of floating points in JavaScript follows the IEEE-754 format. It is a double-precision format where 64 bits are allocated for every floating point.
The displaying of these floating values could be handled using these methods:
Table of Content
- Using toFixed() Method
- Using toPrecision() Method
- Using toExponential() Method
Contact Us