Currency Support For The Win

Daily Standup

I got a flash of inspiration to dust off the value app and add currency support. Well actually not that inspired…I use the app, and I spend money in a different currency now 😝

toLocaleString

One vanilla JS method I was reminded of was toLocalString() which makes displaying currencies super easy. My recollection of this was a bit spotty, and I thought I may need to use a library or something robust to work with currencies, but turns out it’s normal vanilla JavaScript for the win.

This method takes a locale (what kind of numbers to use) and some options, which include currency options:

parseFloat(price).toLocaleString(undefined, {
maximumFractionDigits: 2,
style: "currency",
currency: userCurrency,
currencyDisplay: "symbol"});

When the locale is set to undefined, it will use whatever type of numbers the browser detects as that user’s computer default. So that’s Western numbers, or Japanese, or Arabic, Thai, etc. maximumFractionDigits limits the float to two decimal places; this is necessary because my prices are being updated every time someone uses a Thing, and the number isn’t always rounded to 2 decimals like a normal price. The kicker is setting style to currency, which also requires a specific currency to be selected. In my case I’ve set this to be either a currency selected by the user, or US dollars:

<% var userCurrency = thing.purchaseCurrency || "USD" %>

The currency does have to be the 3-character ISO code for global currencies. Finally symbol ensures it displays the $£€’s (etc) with the number.

Currency Support Is Implemented!

And that was it! I added a new field for the user to set the currency for each new thing in all of the views and voila. Since I’m not really doing any exchange rates on the site (yet!) it was a pretty straightforward implementation.

Up Next

Before deploying this I’m also going to make it so that a user can set a default currency on their account—one less selection to make when adding a new thing. Should have that going in the next couple of days. So the userCurrency variable above will change slightly:

<% var userCurrency = thing.purchaseCurrency || user.defaultCurrency %>

To be continued…!