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.
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.