JavaScript num.toPrecision([digits]) method


The num.toPrecision([digits]) method in JavaScript is used to format a number to a specified length, representing it in either fixed-point or exponential notation. This method is particularly useful when you want to control the total number of significant digits in the output.

Syntax:

num.toPrecision([digits])
  • num: The number you want to format.
  • digits (optional): An integer specifying the total number of significant digits to include in the output. This value must be between 1 and 100. If omitted, the method defaults to the number of digits needed to represent the number accurately.

Return Value:

  • Returns a string representation of the number formatted to the specified precision.

Example Usage:

  1. Basic Usage:

    let num1 = 123.456; console.log(num1.toPrecision()); // "123.456" (default precision) console.log(num1.toPrecision(5)); // "123.46" (rounded to 5 significant digits) console.log(num1.toPrecision(2)); // "1.2e+2" (scientific notation for significant digits)
  2. Using with Small Numbers:

    let num2 = 0.000123456; console.log(num2.toPrecision(3)); // "0.000123" (3 significant digits) console.log(num2.toPrecision(4)); // "1.235e-4" (4 significant digits in scientific notation)
  3. Using with Large Numbers:

    let num3 = 9876543210; console.log(num3.toPrecision(3)); // "9.88e+9" (3 significant digits in scientific notation) console.log(num3.toPrecision(5)); // "9.8765e+9" (5 significant digits)
  4. Rounding Behavior:

    • The method rounds the number based on the specified precision:
    let num4 = 2.34567; console.log(num4.toPrecision(4)); // "2.346" (rounded to 4 significant digits)
  5. Invalid Input:

    • If the digits argument is outside the valid range (1-100), a RangeError will be thrown:
    console.log(num1.toPrecision(101)); // RangeError: toPrecision() digits argument must be between 1 and 100

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.toPrecision([digits]) method in JavaScript is a flexible way to format numbers to a specific total number of significant digits. It handles both fixed-point and scientific notation, depending on the value and the specified precision. This method is especially useful in scenarios where you need to control the output of numerical data for readability or reporting purposes.