JavaScript/React - 加拿大法语的货币格式

问题描述 投票:0回答:1

我正在尝试编写一个函数,表示“如果 URL 包含 /fr,则将法语格式应用于定价。否则,如果 URL 包含 /en,则保留默认定价”。

在加拿大法语中,数字的格式略有不同。示例:19 304,45 $ 而不是 $19,304.45。

我的以下尝试不起作用。如何更正我的代码以使其正常工作?

格式价格函数:

export function formatPrice(price: any) {
  const language = window.location.pathname.includes("/fr") ? "fr" : "en";
  const options = {
    style: "currency",
    currency: "CAD",
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  };

  return price.toLocaleString(language, options);
}

用途:

<Td className="align-right reg-price">
    ${formatPrice(Number(equipment["regular-price"]?.text).toLocaleString())}
</Td>
<Td className="align-right sale-price">
    <strong>${formatPrice(Number(equipment["sale-price"]?.text).toLocaleString())}</strong>
</Td>
javascript reactjs localization currency-formatting
1个回答
0
投票

问题:

toLocaleString
方法主要用于根据语言和区域格式化数字,但它可能不适合格式化具有特定符号和位置的货币。
toLocaleString
中的语言参数需要 BCP 47 语言标记,“fr”或“en”可能不足以进行货币格式设置。

解决方案: 您可以使用

Intl.NumberFormat
构造函数,它允许您指定格式化数字(包括货币)的语言和样式。

export function formatPrice(price: any) {
  const language = window.location.pathname.includes("/fr") ? "fr-CA" : "en-CA";
  const options = {
    style: "currency",
    currency: "CAD",
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  };

  return new Intl.NumberFormat(language, options).format(price);
}
© www.soinside.com 2019 - 2024. All rights reserved.