How to Format a Number to 2 Decimal Places in JavaScript
In JavaScript, formatting numbers to two decimal places is a common requirement for displaying numerical data, especially when dealing with currencies or precise measurements. There are a couple of ways to do this. We’ll cover them in this article.
How to use thetoFixed
method to format a number to 2 decimal places?
The toFixed
method converts a number into a string, rounding to a specified number of decimal places. It's the most straightforward way to format a number to two decimal places.
const number = 123.456; const formattedNumber = number.toFixed(2); console.log(formattedNumber); // Output: "123.46"
How to use thetoLocaleString
method in formatting numbers to 2 decimal places?
For more control over formatting, including localization options, use thetoLocaleString
. This method lets you specify the number of decimal places while considering the local numbering system.
const number = 123.456; const formattedNumber = number.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); console.log(formattedNumber); // Output: "123.46"
Rounding using Math functions
In some cases, you might want to perform rounding operations before formatting. This approach gives you control over how rounding is handled (e.g., Math.round
, Math.ceil
, Math.floor
).
const number = 123.456; const roundedNumber = Math.round(number * 100) / 100; console.log(roundedNumber.toFixed(2)); // Output: "123.46"
Selecting the right method depends on your specific needs—toFixed
for simple rounding and conversion to a string, toLocaleString
for localized formatting, and math functions for more control over rounding. JavaScript's flexibility allows for precise and readable numeric presentations.
Invite only
We're building the next generation of data visualization.
How to Remove Characters from a String in JavaScript
Jeremy Sarchet
How to Sort Strings in JavaScript
Max Musing
How to Remove Spaces from a String in JavaScript
Jeremy Sarchet
Detecting Prime Numbers in JavaScript
Robert Cooper
How to Parse Boolean Values in JavaScript
Max Musing
How to Remove a Substring from a String in JavaScript
Robert Cooper