Reputation: 1870
I have been searching for hours and there appears to be no simple way to present a number in local currency. I have gotten very close but I can't get the last piece of info, being the local currency code ('USD' for United States in the below example)
using navigator.language I can get the local format ('en-US', etc), which is great. one step closer to a perfect global currency formatter, but still cannot get the currency code!
const formatter = new Intl.NumberFormat(navigator.language, {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 0
});
I have found web sites that have large tables with every currency code for each country. I could try importing all that data into a table and then mapping a gps location or browser location to one of those but that is going to be messy. Other option is to let the user selected from a drop-down, but again that is very messy.
Are we really in the year 2020 and no one has thought to create a dynamic way to get the local currency code to the browser?
Has anyone solved this?
Upvotes: 1
Views: 525
Reputation: 1870
Here's what I came up with. Possibly the world's first global currency formatter. Should work perfectly in any country. (requires jQuery):
function formatNumberToLocalCurrency(amount=0, refresh=false) {
if (refresh || !localStorage.geoplugin_currencyCode) {
$.getJSON('http://www.geoplugin.net/json.gp?jsoncallback=?', function (data) {
localStorage.geoplugin_currencyCode = data.geoplugin_currencyCode;
});
}
const formatter = new Intl.NumberFormat(navigator.language || 'en-US', {
style: 'currency',
currency: localStorage.geoplugin_currencyCode || 'USD',
minimumFractionDigits: 0
});
return formatter.format(amount);
}
Upvotes: 1