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');
}
您应该测试该函数在所有浏览器/设备上的执行方式,尽管它应该可以在所有主要的更新浏览器上正常运行。
这篇关于在不同的浏览器上提供不同的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在不同的浏览器上提供不同的输出
基础教程推荐
- npm start 错误与 create-react-app 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
