Kodeclik Blog


Javascript toFixed()

The toFixed() method is a built-in method in JavaScript that is used to format a number using fixed-point notation. It rounds a number to a specified number of decimal places by either adding zeros to increase the length or by rounding off to reduce the length.
The syntax for using toFixed() is num.toFixed(len), where num is the number to be formatted using fixed-point notation and len is the number of digits after the decimal point in which num will be formatted. It is important to note that the toFixed() method returns a string (not a number) that represents the number num with len digits after the decimal point.
A realistic scenario to use toFixed() is when you need to display a number with a fixed number of decimal places, such as when displaying currency.
Consider the code below:
In this example, we first create a label and input field for the user to enter the currency value. We also create a button with the ID toFixedButton that the user can click to format the currency value. We then create a paragraph with the ID formattedCurrency where we will display the formatted currency value. We get the input field, button, and paragraph using their respective IDs. We then add an event listener to the button that listens for a click event. When the button is clicked, we get the value of the input field and convert it to a float using parseFloat(). We then use toFixed() to format the currency value to two decimal places and store the result in a variable called formattedValue. Finally, we display the formatted currency value on the webpage using innerHTML.
Here are two examples of the above code in action:
In the above first example,toFixed() loses one digit of resolution because we are asking for only two digits.
In our second example, as you can see, toFixed() pads a zero to reach our desired resolution.
Here are some key points to keep in mind when using toFixed().
len is an optional parameter. If len is not passed as a parameter, the default value is len = 0, which rounds the number to a whole number. Further, len must be in the range of 1 to 100. Otherwise, a RangeError is thrown.
Also note that if the precision is too high, it can return unexpected results because decimal fractional numbers cannot be represented precisely in floating-point.toFixed() is ideal for use cases such as the above.
If you liked this blogpost checkout our blogpost on Javascript trimEnd().
Want to learn Javascript with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.
  • ABOUT

Copyright @ Kodeclik 2024. All rights reserved.