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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee