In this blog post, we will learn how to format numbers in JavaScript using several common methods. Formatting numbers can be useful for displaying currency, percentages, decimal places, and more.
ToLocaleString Method
The toLocaleString method is a built-in JavaScript function that takes a number and returns a formatted string with the appropriate localization. This method is useful for displaying numbers as they would appear to a user of a specific locale.
Here is an example of using the toLocaleString method to format a number:
const number = 123456.789; const formattedNumber = number.toLocaleString('en-US', { style: 'currency', currency: 'USD' }); console.log(formattedNumber); // Output: $123,456.79
Number.toFixed Method
The toFixed method is another built-in JavaScript function that takes a single argument, the number of decimal places you want to display, and returns a formatted string with the specified decimal places. This method is useful for displaying numbers with a fixed number of decimal places.
Here is an example of using the toFixed method to format a number:
const number = 123456.789; const formattedNumber = number.toFixed(2); console.log(formattedNumber); // Output: 123456.79
Using Regular Expressions
If you need more control over the formatting of a number, you can use regular expressions with the replace method. This method can be useful for adding thousands separators or other custom formatting.
Here is an example of using a regular expression to format a number with thousands separators:
const number = 123456789.123; const formattedNumber = number.toString().replace(/B(?=(d{3})+(?!d))/g, ","); console.log(formattedNumber); // Output: 123,456,789.123
Conclusion
In this blog post, we learned how to format numbers in JavaScript using the toLocaleString, toFixed, and replace methods with regular expressions. These techniques can be applied for displaying numbers in a variety of formats, including currency, percentages, decimal places, and more.