I’m trying to build a function in JavaScript that takes a float and returns a nicely formatted string.
Ideally, I’d like to use a reliable JavaScript format currency method that handles things like commas and decimal places properly. How can I achieve this?
If you’re aiming for a modern and flexible way to format currency, I’d say go with Intl.NumberFormat. It’s built right into JavaScript and super handy.
function formatCurrency(amount) {
return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(amount);
}
console.log(formatCurrency(2500)); // $2,500.00
This is my go-to approach when I need a reliable JavaScript format currency solution that also respects localization settings and it’s super readable too!
If you prefer doing things manually (say you’re not targeting multiple locales), here’s a basic approach using toFixed and some string trickery:
function formatCurrency(amount) {
return "$ " + amount.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
}
console.log(formatCurrency(2500)); // $ 2,500.00
While this method doesn’t use Intl, it works well when you need a lightweight javascript format currency approach without relying on built-in internationalization.
If your app deals with complex number formatting or you want additional features, using a library like Numeral.js is totally worth it.
numeral(2500).format('$0,0.00'); // $2,500.00
Once you’ve got the library loaded, it makes JavaScript currency formatting tasks a breeze. Plus, it’s super customizable if you want different symbols or decimal styles.