JavaScript: Format Number to 2 Decimal Places

How can I format a number in JavaScript to always show 2 decimal places, rounding where applicable?

For example, I want to achieve the following:

number display 1 1.00 1.341 1.34 1.345 1.35

I’ve been using parseFloat(num).toFixed(2);, but it’s displaying 1 as 1 instead of 1.00. I’m looking for a solution related to 2 decimal places javascript.

Using toFixed(): You can use the toFixed() method directly on the number. This method converts the number to a string, ensuring the specified number of decimals. For example:

function formatNumber(num) {
    return Number(num).toFixed(2);
}
console.log(formatNumber(1));       // Outputs: "1.00"
console.log(formatNumber(1.341));   // Outputs: "1.34"
console.log(formatNumber(1.345));   // Outputs: "1.35"

This approach keeps 2 decimal places javascript formatting simple and is great for straightforward display needs.

Another solid method is using Intl.NumberFormat. This built-in JavaScript object lets you format numbers with locale settings. With this, you can specify the minimum and maximum fraction digits to ensure 2 decimal places javascript formatting:

function formatNumber(num) {
    return new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(num);
}
console.log(formatNumber(1));       // Outputs: "1.00"
console.log(formatNumber(1.341));   // Outputs: "1.34"
console.log(formatNumber(1.345));   // Outputs: "1.35"

This method comes in handy if you’re working with internationalization or want a more robust solution.

Adding to what Tim mentioned, you could also achieve 2 decimal places javascript formatting by combining rounding with template literals. This way, you ensure both accurate rounding and proper display:

function formatNumber(num) {
    return `${(Math.round(num * 100) / 100).toFixed(2)}`;
}
console.log(formatNumber(1));       // Outputs: "1.00"
console.log(formatNumber(1.341));   // Outputs: "1.34"
console.log(formatNumber(1.345));   // Outputs: "1.35"

Here, the combination of rounding and formatting ensures consistency, while template literals help keep things concise.