在 JavaScript 或 jQuery 中获取用户的货币区域设置很热吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33561412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hot to get user’s regional settings for currency in JavaScript or jQuery?
提问by coeurdange57
I'm trying to format some numbers with jQuery. I would like to get the user's regional settings for currency and number, in order to implement the correct format (obtain the decimal separator).
我正在尝试使用 jQuery 格式化一些数字。我想获取用户对货币和数字的区域设置,以实现正确的格式(获取小数点分隔符)。
Is it possible to retrieve these parameters with jQuery or JavaScript?
是否可以使用 jQuery 或 JavaScript 检索这些参数?
回答by dakab
Use Number.toLocaleString()
with style:'currency'
:
使用Number.toLocaleString()
有style:'currency'
:
(73.57).toLocaleString('de-DE',{style:'currency',currency:'EUR'}); // German: 73,57
(73.57).toLocaleString('en-US',{style:'currency',currency:'EUR'}); // American: 73.57
Note that:
注意:
- This does not getregional settings, but providesoutput in regional settings.
- If you want your locale to be determined dynamically, use
navigator.language
. - There are many other means aside from this native approach; for starters, take a look at accounting.jsor Stack Overflow answers like this one.
- 这不会获得区域设置,而是提供区域设置中的输出。
- 如果您希望动态确定您的语言环境,请使用
navigator.language
. - 除了这种原生方法之外,还有许多其他方法;对于初学者,看看accounting.js或堆栈溢出回答这样一个。
Using Intl.NumberFormat.format()
, you can achieve identical results, with the NumberFormat
and the general Intl
objects offering versatile options and methods with a main focus on language sensitivity.
使用Intl.NumberFormat.format()
,您可以获得相同的结果,而NumberFormat
和一般Intl
对象提供了主要关注语言敏感性的多功能选项和方法。
new Intl.NumberFormat('de-DE',{style:'currency',currency:'EUR'}).format(73.57); // DE: 73,57
new Intl.NumberFormat('en-US',{style:'currency',currency:'EUR'}).format(73.57); // US: 73.57
回答by David Votrubec
There is a jQuery plugin for it - https://github.com/dansingerman/jQuery-Browser-Language
有一个 jQuery 插件 - https://github.com/dansingerman/jQuery-Browser-Language
See this SO answer for more info JavaScript for detecting browser language preference
有关更多信息,请参阅此 SO 答案JavaScript 用于检测浏览器语言偏好