【问题标题】:Using Intl.NumberFormat with 'de' locale and 'percent' style使用带有“de”语言环境和“百分比”样式的 Intl.NumberFormat
【发布时间】:2017-08-19 15:42:41
【问题描述】:
我尝试使用 Intl.NumberFormat 对象来格式化我的用户输入。
在我的 javascript 项目中,我创建组件并尝试如下使用它;
const simpleFormat = new Intl.NumberFormat('de-DE', {style: 'percent'});
simpleFormat.format(12345678)
当我预期 123.456,78% 时,结果为 123.456.78%
逗号和点。分隔符适用于相同语言环境的货币样式。但它似乎不适用于“百分比”模式。有人有这个问题的解决方案吗?
【问题讨论】:
标签:
javascript
firefox
localization
number-formatting
【解决方案1】:
首先,格式化为百分比 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);