对于Firefox低于100,000的母羊,不会显示toLocaleString千位分隔符

问题描述

我在Firefox上,如果我将语言环境设置为“ ee”,则将其设置为toLocaleString。千位分隔符不会出现在100,000以下。

(1111).toLocaleString("ee-gh")
"1111"
(10000).toLocaleString("ee-gh")
"10000"
(123456).toLocaleString("ee-gh")
"123,456"
console.log((1111).toLocaleString("ee-gh"));
console.log((10000).toLocaleString("ee-gh"));
console.log((123456).toLocaleString("ee-gh"));

即使useGrouping设置为true

(1234).toLocaleString("ee-gh",{useGrouping: true})
"1234"

为什么母羊会发生这种情况?如果我将语言环境设置为英语,它将可以正常工作

(1234).toLocaleString("en-us")
"1,234"
console.log((1234).toLocaleString("ee-gh",{useGrouping: true}));

解决方法

语言环境ee的最小分组数字设置为3,如CLDR survey tool所示。 如果分组分隔符在left side of the first grouping separator.上至少包含3位数字,则会得到该分隔符。这是一件罕见的事情,ee是CLDR 38中唯一具有这种值的语言环境。这适用于Chrome和Firefox。

我有办法解决这个问题。利用格式格式化零件。 分组分隔符是通过在第一个分组分隔符的左侧按百万位格式(4位数字)进行格式化而得到的,因为4是我可以找到的最小分组数字的最大值,然后它每3个使用该符号对未分组的整数进行分组数字。

function format_no_minimum_grouping_digits(value_to_format,locale,options) {
    // Create a number formatter
    const formatter = new Intl.NumberFormat(locale,options);
    const formatter_options = formatter.resolvedOptions();
    // Check if grouping is disabled 
    if (!formatter_options.useGrouping
        // The POSIX locale have grouping disabled
        || formatter_options.locale === "en-US-u-va-posix"
        // Bulgarian currency have grouping disabled
        || (new Intl.Locale(formatter_options.locale).language === "bg") && formatter_options.style === "currency") {
        // If yes format as normal
        return formatter.format(value_to_format);
    };
    // Otherwise format it to parts
    const parts = formatter.formatToParts(value_to_format);
    // Check if the grouping separator isn't applied
    const groupSym = parts.find(part => part.type === "group") === undefined ? new Intl.NumberFormat(locale,options).formatToParts(10 ** 6)[1].value : undefined;
    // If the grouping separator isn't applied,group them
    return parts.map(({type,value}) => (type === "integer" && groupSym) ? value.replace(/\B(?=(\d{3})+$)/g,groupSym) : value).join('');
}