使用不带货币符号的 Intl.NumberFormat 进行货币格式化

Koc*_*r4d 12 javascript number-formatting

我正在尝试使用 Intl 作为默认货币格式化程序,它几乎是完美的。

\n

Intl.NumberFormat()使用构造函数中的示例:

\n
const number = 123456.789;\n\nconsole.log(new Intl.NumberFormat(\'de-DE\', { style: \'currency\',\ncurrency: \'EUR\' }).format(number)); // expected output: "123.456,79 \xe2\x82\xac"\n \n// the Japanese yen doesn\'t use a minor unit \nconsole.log(new Intl.NumberFormat(\'ja-JP\', { style: \'currency\', currency: \'JPY\'\n}).format(number)); // expected output: "\xef\xbf\xa5123,457"\n
Run Code Online (Sandbox Code Playgroud)\n

这几乎是完美的,但我实际上想从输出中删除该符号。所以我希望看到:

\n
// expected output: "123.456,79"\n// expected output: "123,457"\n
Run Code Online (Sandbox Code Playgroud)\n

我觉得很奇怪,我花了一个多小时寻找解决方案,却只找到了某种替换/修剪的用法。

\n

为什么没有一个选项可以使用所有国际功能来格式化数字,而只删除货币符号?!?

\n

我希望我错过了,说实话。

\n

VLA*_*LAZ 21

实现您想要的效果的一种简单方法是使用String#replace()从字符串中删除货币。为了使这一过程变得更容易,您可以设置currencyDisplay"code"使用 ISO 货币代码 - 与传入的相同currency

const number = 123456.789;

console.log(new Intl.NumberFormat('de-DE', { 
    style: 'currency',
    currency: 'EUR', 
    currencyDisplay: "code" 
  })
  .format(number)
  .replace("EUR", "")
  .trim()
); // 123.456,79
 
// the Japanese yen doesn't use a minor unit 
console.log(new Intl.NumberFormat('ja-JP', { 
    style: 'currency', 
   currency: 'JPY', 
    currencyDisplay: "code" 
  })
  .format(number)
  .replace("JPY", "")
  .trim()
); // 123,457
Run Code Online (Sandbox Code Playgroud)

这可以提取到一个函数中:

const number = 123456.789;

console.log(format('de-DE', 'EUR', number)); // 123.456,79
console.log(format('ja-JP', 'JPY', number)); // 123,457

function format (locale, currency, number) {
  return new Intl.NumberFormat(locale, { 
    style: 'currency', 
    currency, 
    currencyDisplay: "code" 
  })
  .format(number)
  .replace(currency, "")
  .trim();
}
Run Code Online (Sandbox Code Playgroud)


另一种允许您进行更多控制的替代方案是使用Intl.NumberFormat#formatToParts()数字的格式,但为您提供可以以编程方式使用和操作的令牌。例如,使用 和 方法,locale = "de-DE"currency = "EUR"将得到以下输出:

[
  {
    "type": "integer",
    "value": "123"
  },
  {
    "type": "group",
    "value": "."
  },
  {
    "type": "integer",
    "value": "456"
  },
  {
    "type": "decimal",
    "value": ","
  },
  {
    "type": "fraction",
    "value": "79"
  },
  {
    "type": "literal",
    "value": " "
  },
  {
    "type": "currency",
    "value": "EUR"
  }
]
Run Code Online (Sandbox Code Playgroud)

这意味着您可以轻松过滤掉"type": "currency"并将其余部分组合成一个字符串。例如:

[
  {
    "type": "integer",
    "value": "123"
  },
  {
    "type": "group",
    "value": "."
  },
  {
    "type": "integer",
    "value": "456"
  },
  {
    "type": "decimal",
    "value": ","
  },
  {
    "type": "fraction",
    "value": "79"
  },
  {
    "type": "literal",
    "value": " "
  },
  {
    "type": "currency",
    "value": "EUR"
  }
]
Run Code Online (Sandbox Code Playgroud)