JavaScript Number toFixed() Method

JavaScript Number toFixed() method is “used to convert a number to fixed-point notation (rounding the result where necessary) and return its value as a string.”

Syntax

toFixed(digits)

Parameters

digits: The number of digits to appear after the decimal point; should be between 0 and 100, inclusive. If this argument is omitted, it is treated as 0.

Return value

It returns a string representing the given number using fixed-point notation.

Exceptions

  1. RangeError: It is thrown if digits are not between 0 and 100 (inclusive).
  2. TypeError: It is thrown if this method is invoked on an object that is not a Number.

Example 1: How to Use toFixed() Method

let main_num = 123.456789;

console.log(main_num.toFixed());
console.log(main_num.toFixed(1));
console.log(main_num.toFixed(2));

Output

123
123.5
123.46

Example 2: Using toFixed() with negative numbers

let num = -123.4567;

console.log(num.toFixed(2));

Output

-123.46

Example 3: Simplified version of the toFixed() method that works for most common scenarios

function toFixed(number, precision = 0) {
  // Check if precision is within the valid range
  if (precision < 0 || precision > 20) {
    throw new RangeError('toFixed() digits argument must be between 0 and 20');
  }

  // Handle special cases
  if (isNaN(number)) {
    return 'NaN';
  }

  if (number >= Math.pow(10, 21) || number <= -Math.pow(10, 21)) {
    return number.toString();
  }

   // Multiply the number by the required power of 10
   let shifted = Math.round(number * Math.pow(10, precision));

  // Convert to string
  let result = (shifted / Math.pow(10, precision)).toString();

  // Add zeros if required
  if (precision > 0) {
    let dotIndex = result.indexOf('.');
    if (dotIndex === -1) {
      result += '.';
      dotIndex = result.length - 1;
    }
    while (result.length <= dotIndex + precision) {
      result += '0';
    } 
 }

  return result;
}

// Test
console.log(toFixed(123.4567, 2));
console.log(toFixed(-123.4567, 3));
console.log(toFixed(0.005, 2));
console.log(toFixed(1.005, 2));

Output

JavaScript Number toFixed()

Browser Compatibility

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

That’s it!

Related posts

How to Print a Number with Commas as Thousands Separators in JavaScript

Leave a Comment