Format a number to 2 Decimal places in JavaScript


Borislav Hadzhiev

Last updated: Jul 25, 2022


Photo from Unsplash

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 called 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 only be called on a number. 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
The toFixed method returns a string. If you need the result to be a number, call the parseFloat method on the string.
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. The language doesn't keep insignificant trailing zeros after converting a string to a number.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.