Format a number to 2 Decimal places in JavaScript


Borislav Hadzhiev

Sat Oct 23 20212 min read

Format a number to 2 Decimal places in JavaScript #

Use the toFixed() method to format a number to 2 decimal places, e.g. num.toFixed(2). The toFixed method takes a parameter, representing how many digits should appear after the decimal and returns the result.

const num1 = 13; const ex1 = num1.toFixed(2); console.log(ex1); // 👉️ 13.00 const num2 = 13.33; const ex2 = num2.toFixed(2); console.log(ex2); // 👉️ 13.33 // 👇️ If your number is wrapped in a string // call parseFloat first const str1 = '13.1'; const ex3 = parseFloat(str1).toFixed(2); console.log(ex3); // 👉️ 13.10 // 👇️ examples with rounding const num4 = 13.505; const ex4 = num4.toFixed(2); console.log(ex4); // 👉️ 13.51 const num5 = 13.504; const ex5 = num5.toFixed(2); console.log(ex5); // 👉️ 13.50

We used the toFixed method on the number, passing it 2 as a parameter.

The only parameter the toFixed method takes is how many digits we want to appear after the decimal point.

The toFixed method should be called on a number, so if you have a number wrapped in a string, call the parseFloat function first.

The toFixed method:

  • rounds the number if necessary
  • pads the decimal places with zeros if necessary
Note that the toFixed method returns a string. If you need the result to be a number, call the parseFloat method on the result.
const num = 13.5; const str = num.toFixed(2); console.log(typeof str); // 👉️ string const parsed = parseFloat(str); console.log(parsed); // 👉️ 13.5 console.log(typeof parsed); // 👉️ number

Note that we don't have a trailing zero after we converted the string to a number.

You can't have numbers with trailing zeros in JavaScript because every time you convert a string with trailing zeros to a number, they get removed.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.