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 😝
One vanilla JS method I was reminded of was
This method takes a locale (what kind of numbers to use) and some options, which include currency options:
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
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.
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.
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…!