繁体   English   中英

如何在 JavaScript 中确定千位分隔符

[英]How to determine thousands separator in JavaScript

为了使toLocaleString起作用,浏览器/JavaScript 必须知道用户的语言环境以及特定语言环境是使用“,”还是“.”。 对于千位分隔符。 是否可以访问这些数据以便我们可以确定千位分隔符是什么?

如果没有,我们可以使用这样的函数......

var thousandsSeparator = (function(){
    if (typeof Number.prototype.toLocaleString === 'function') {
        var num = 1000;
        var numStr = num.toLocaleString();
        if (numStr.length == 5) {
            return numStr.substr(1, 1);
        }
    }
    return ","; // fall-back
})();

...但这感觉像是一个不必要的黑客。

进一步挖掘,我发现了Intl.NumberFormat 我觉得这更优雅...

const thousandsSeparator = (function(){
    if (typeof Intl !== 'object') {
        return ','; // fallback
    }
    // Get the formatting object for your locale
    const numFormat = new Intl.NumberFormat();
    // The resolved.pattern will be something like "#,##0.###"
    return numFormat.resolved.pattern.substr(1,1);
})();

或者如果你真的需要它超简洁......

const thousandsSeparator = (Intl) ? (new Intl.NumberFormat()).resolved.pattern.substr(1,1) : ",";

兼容性警告(2015):

  • 出于某种原因,Safari 可能不支持Intl对象——http: //caniuse.com/#feat=internationalization——尽管它是标准 ECMAScript 的一部分。
  • 虽然Intl对象可能存在于某些 ECMAScript 标准浏览器中,但上面的代码仅适用于 Chrome
  • 遗憾的是,Firefox 40 和 IE 11 目前在numFormat没有已resolved属性。

一个优雅的跨浏览器解决方案仍然存在......

更新(2021):

IntlnumFormat.resolved可能在非 Chrome 浏览器中具有更好的浏览器支持。 请参阅评论以获取最新信息。

很简单,我猜。 这应该可以帮助您开始使用这个 ES6 解决方案

function getThousandSeparator(locale){
  const mapperRE = /(.{1})\d{3}(\D)\d$/,
    digitRE = /\d/,
    formattedValue = (new Intl.NumberFormat(locale?? navigator.language)).format(1000.1);
  let [_,thousand, decimal] = mapperRE.exec(formattedValue) ?? [null,null,null];
  //In case the captured position is number it means there's no thousand separator
  if(digitRE.test(thousand)) 
    thousand = '';
  return {thousand, decimal}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM