quot;toLocaleStringquot; giving different output on different browsers(在不同的浏览器上提供不同的输出)
问题描述
var num = 1239128938213092131823;
num.toLocaleString('en-IN', { maximumSignificantDigits: 3, style: 'currency', currency: 'INR'});
在铬上:
在Firefox上:
两个浏览器中的逗号模式输出不同。火狐输出是我想要的,我也需要相同的输出在Chrome中。有什么解决方法吗?
编辑: 最近我在Chrome版本53.0.2785.116上检查了一下,现在Chrome输出和Firefox输出是一样的。
推荐答案
更新我的答案-我最初认为这是一个错误的说法是不正确的。
再次更新-找到Chrome显示的原因Rs.
该错误指的是其他内容,因为您确实是在传递区域设置。将区域设置更改为使用印度使用的印地语(hi-IN
),我能够获得以下代码以在两个浏览器上显示正确格式的数字:
num.toLocaleString('hi-IN', {maximumSignificantDigits: 3, style: 'currency', currency: 'INR'});
但是,您会注意到Chrome将显示Rs.
而不是卢比符号。This is an intentional decision by Chrome:
使用"Rs"。而不是印度卢比标志(U+20A8),其中字体 并非所有平台都提供支持。
为了获得一些一致性,您也可以传递currencyDisplay: 'code'
,这将用"INR"替换卢比符号。这在Chrome和Firefox上都运行得很好。
num.toLocaleString('hi-IN', {maximumSignificantDigits: 3, style: 'currency', currency: 'INR', currencyDisplay: 'code'});
您可能希望检查是否提供区域设置和/或Intl支持。这可以通过following code from MDN实现(尽管如上所述,可用性不能保证类似的实现):
function toLocaleStringSupportsLocales() {
var number = 0;
try {
number.toLocaleString('i');
} catch (e) {
return e.name === 'RangeError';
}
return false;
}
function toLocaleStringSupportsOptions() {
return !!(typeof Intl == 'object' && Intl && typeof Intl.NumberFormat == 'function');
}
if(toLocaleStringSupportsLocales()) {
if(toLocaleStringSupportsOptions()) {
console.log(num.toLocaleString('hi-IN', {maximumSignificantDigits: 3, style: 'currency', currency: 'INR', currencyDisplay: 'code'}));
} else {
// Browser supports locales but does not support Intl options
console.log(num.toLocaleString('hi-IN'));
}
} else {
// Browser does not support locales
console.error('Cannot format number - locales not supported');
}
您应该测试该函数在所有浏览器/设备上的执行方式,尽管它应该可以在所有主要的更新浏览器上正常运行。
这篇关于在不同的浏览器上提供不同的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在不同的浏览器上提供不同的输出


- 400或500级别的HTTP响应 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01