[英]Javascript Global Format Currency
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)
我已经非常接近了,但我无法获得最后一条信息,即当地货币代码(以下示例中的美国为“USD”)
using navigator.language I can get the local format ('en-US', etc), which is great.使用 navigator.language 我可以获得本地格式('en-US'等),这很棒。 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.我发现 web 网站有大表格,每个国家/地区的每个货币代码。 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.
我可以尝试将所有这些数据导入表中,然后将 gps 位置或浏览器位置映射到其中之一,但这会很混乱。 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?我们真的在 2020 年,没有人想过创建一种动态方式将本地货币代码获取到浏览器吗?
Has anyone solved this?有没有人解决这个问题?
Here's what I came up with.这就是我想出的。 Possibly the world's first global currency formatter.
可能是世界上第一个全球货币格式化程序。 Should work perfectly in any country.
应该在任何国家都能完美运行。 (requires jQuery):
(需要 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.