Joe Richardson

Handling currency with a simple function

When working on projects there always seems to be a struggle when it comes to handling currency. I usually go for the approach of using a library that handles this for me, simply because I’ve never actually thought it would be worth trying to write my own. There is a shit load of libraries already out there and I’ve always assumed it was quite a complex thing to write yourself.

The Function

I recently discovered that number.toLocaleString() has a collection of params you can pass to it (locale, currency, style etc) after experimenting with the params I’ve created a really simple function to handle currency.

function formatPrice(number, locale, currency) {
    return number.toLocaleString(locale, {
        style: 'currency',
        currency: currency

// Usage:
formatPrice(5000, 'en-US', 'usd') // $5,000.00

Of course like anything I’m sure lots of people already know about this but for those who don’t then this really is a great thing to be aware of.

Short and sweet but if you have any questions, reach out