使用具有 'de' 语言环境和 'percent' 样式的 Intl.NumberFormat

Using Intl.NumberFormat with 'de' locale and 'percent' style

我尝试使用 Intl.NumberFormat 对象来格式化我的用户输入。 在我的 javascript 项目中,我创建了组件并尝试如下使用它;

const simpleFormat = new Intl.NumberFormat('de-DE', {style: 'percent'});

simpleFormat.format(12345678)

它给我的结果是 123.456.78% 当我期待 123.456,78% 逗号和点。分隔符在相同区域设置的货币样式下工作良好。但它似乎不适用于 'percent' 模式。有人能解决这个问题吗?

首先,将格式设置为百分比 12345678 会生成 1.234.567.800% 而不是“123.456.78”的字符串%" 那是因为,简单地说,小数 12345678 乘以 100 得到百分比值(这样小数 1 等于 100%)。

另一个问题是 percent 样式默认不使用任何小数,因此您需要使用 maximumFractionDigits 选项以便如果需要,它会使用它们。

综上所述,如果你想 23.456,78% 你需要:

const simpleFormat = new Intl.NumberFormat('de-DE', {
  style: 'percent',
  maximumFractionDigits: 2,
});
let perc = simpleFormat.format(1234.5678);
console.log(perc);