JS Intl.NumberFormat 货币不能有 maximumFractionDigits 0

Nik*_*rov 9 javascript google-chrome

我正在使用 JavaScript Intl 对象,我想将数字(例如 150)格式化为“£150”。对于 Chrome,直到更新到版本 59 这段代码才完美运行:

var GBPFormatter = new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'GBP',
      maximumFractionDigits: 0
  });
Run Code Online (Sandbox Code Playgroud)

但现在它说“maximumFractionDigits”不能为0,在阅读https://developer.mozilla.org/后,我发现GBP的maximumFractionDigits不能小于2。

一切都很好,但我仍然需要“£150”而不是“£150.00”。我仍然可以使用 Intl 对象并使其看起来像我需要的方式的任何想法。

PS 我知道我可以让我自己的函数剂量相同,但考虑到我不仅有英镑而且还有更多的货币,我更愿意坚持使用现成的解决方案。

小智 14

您可以将maximumFractionDigits选项设置为0喜欢,但值需要高于minimumFractionDigits。由于 的默认值minimumFractionDigits高于0此货币的默认值,因此您需要手动设置它们以获得所需的值:

var GBPFormatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'GBP',
  minimumFractionDigits: 0,
  maximumFractionDigits: 0
});

console.log(GBPFormatter.format(150)); // Should output "£150"
Run Code Online (Sandbox Code Playgroud)

  • 几个月前你在哪里 :) 这很好用 (2认同)