Format a number to 2 decimal places in JavaScript

You can use the toFixed() method to format a number to 2 decimal places in JavaScript. The toFixed() method takes a number as input, representing the number of digits to appear after the decimal point, and returns a formatted string representing the given number.

const num1 = 12.865
const res1 = num1.toFixed(2)
console.log(res1) // 12.87

const num2 = 19
const res2 = num2.toFixed(2)
console.log(res2) // 19.00

In the above examples, we called the toFixed() method on the number, passing it 2 as a parameter to format the number to 2 decimal places.

The only parameter toFixed() takes is the number of digits to appear after the decimal point. The value must be between 0 and 100 inclusive. If this argument is skipped, it is treated as 0. If you pass a value greater than 100, a RangeError is thrown:

const num1 = 17.8654553
const res1 = num1.toFixed()
console.log(res1) // 18

const num2 = 55.3469
const res2 = num2.toFixed(120)
console.log(res2)
// RangeError: toFixed() digits argument must be between 0 and 100

Using toFixed() with negative numbers may produce unexpected results. You need to group the negative number expression to get a formatted string:

const res1 = -7.892.toFixed(2)
console.log(res1) // -7.89
console.log(typeof res1) // number --> ❌

const res2 = (-7.892).toFixed(2)
console.log(res2) // -7.89
console.log(typeof res2) // string -->  ✅

If the number is wrapped in a string, you need to convert the string to a number first before calling the toFixed() method:

const str = '22.567'
const res = parseFloat(str).toFixed(2)
console.log(res) // 22.57

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.