JavaScript num.toFixed([digits]) method


The num.toFixed([digits]) method in JavaScript is used to convert a number to a string, representing the number in fixed-point notation. This method is useful for formatting numbers to a specific number of decimal places, which is often necessary for displaying currency or other precise values.

Syntax:

num.toFixed([digits])
  • num: The number you want to format.
  • digits (optional): An integer specifying the number of digits to appear after the decimal point. This value must be between 0 and 20. If omitted, it defaults to 0, meaning the number will be rounded to the nearest integer.

Return Value:

  • Returns a string representation of the number in fixed-point notation with the specified number of decimal places.

Example Usage:

  1. Basic Usage:

    let num1 = 123.456; console.log(num1.toFixed()); // "123" console.log(num1.toFixed(2)); // "123.46" console.log(num1.toFixed(4)); // "123.4560"
  2. Rounding Behavior:

    • The method rounds the number based on the value of the digit immediately after the specified decimal places:
    let num2 = 2.34567; console.log(num2.toFixed(2)); // "2.35" (rounded) console.log(num2.toFixed(4)); // "2.3457" (rounded)
  3. Using with Integers:

    let num3 = 100; console.log(num3.toFixed(2)); // "100.00"
  4. Handling Large Numbers:

    let num4 = 123456789.12345; console.log(num4.toFixed(3)); // "123456789.123"
  5. Invalid Input:

    • If the digits argument is outside the valid range (0-20), a RangeError will be thrown:
    console.log(num1.toFixed(21)); // RangeError: toFixed() digits argument must be between 0 and 20

Special Cases:

  • If the number is NaN, Infinity, or -Infinity, the method will return the string representation of these values ("NaN", "Infinity", or "-Infinity").

Summary:

The num.toFixed([digits]) method is a straightforward way to format numbers to a specified number of decimal places in JavaScript. It is particularly useful for financial calculations and presenting data where precision is required. The method handles rounding and ensures that the output is always in string format, accommodating the specified number of decimal places.