Kodeclik Logo

Our Programs

Courses

Learn More

Schedule

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:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Format Currency</title>
</head>
<body>
<label for="currencyInput">Enter currency value:</label>
<input type="text" id="currencyInput">
<button id="toFixedButton">Format Currency</button>
<p id="formattedCurrency"></p>
<script>
  // Get the input field and button
  const inputField = 
          document.getElementById("currencyInput");
  const toFixedButton = 
          document.getElementById("toFixedButton");
  const formattedCurrency = 
          document.getElementById("formattedCurrency");

  // Add an event listener to the button
  toFixedButton.addEventListener("click", () => {
    // Get the value of the input field
    const currencyValue = 
           parseFloat(inputField.value);
    // Use toFixed() to format the value
    const formattedValue = 
          currencyValue.toFixed(2);
    // Display the formatted currency value
    formattedCurrency.innerHTML = 
          'Formatted currency value: \${formattedValue}';
  });
</script>
</body>
</html>

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:

JavaScript toFixed()

In the above first example,toFixed() loses one digit of resolution because we are asking for only two digits.

JavaScript toFixed()

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.

Kodeclik sidebar newsletter

Join our mailing list

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

About

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.

Copyright @ Kodeclik 2024. All rights reserved.