How to use toFixed() Method In Javascript
The number of decimal places in float values can be set using the toFixed() method. This method converts the number into a string, keeping the specified number of digits after the point. If no value is passed as a parameter, then it takes 0 as the default value i.e. no decimal points are displayed.
Syntax:
number.toFixed(digits)
Example: This example shows the use of the toFixed() method.
Javascript
pi = 3.14159265359; twoPlaces = pi.toFixed(2); fivePlaces = pi.toFixed(5); console.log(twoPlaces); console.log(fivePlaces); |
Output
3.14 3.14159
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