You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript/React加拿大法语CAD货币格式化功能修正求助

问题修正方案

核心问题分析

  1. 参数类型错误:调用formatPrice时,你先把数字转成了字符串(Number(...).toLocaleString()),但formatPrice需要的是数字类型,字符串调用toLocaleString的逻辑完全不符合预期,直接导致格式失效。
  2. Locale参数不精准:只用"fr"或"en"无法确保是加拿大地区的格式,必须指定"fr-CA"(加拿大法语)和"en-CA"(加拿大英语)才能生成目标格式。
  3. 重复添加货币符号:toLocaleString配置style: "currency"后会自动生成带货币符号的字符串,你手动加的$会导致重复显示(比如变成$$19,304.45)。

修正后的formatPrice函数

export function formatPrice(price: any) {
  // 确保传入值转为数字,避免非数字参数报错
  const numPrice = Number(price);
  if (isNaN(numPrice)) return '';

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

  return numPrice.toLocaleString(locale, options);
}

修正后的使用示例

<Td className="align-right reg-price">
    {formatPrice(equipment["regular-price"]?.text)}
</Td>
<Td className="align-right sale-price">
    <strong>{formatPrice(equipment["sale-price"]?.text)}</strong>
</Td>

效果说明

  • 当URL包含/fr时,自动输出加拿大法语格式:19 304,45 $
  • 当URL包含/en时,输出加拿大英语格式:$19,304.45
  • 函数内部新增了数字转换和NaN校验,避免传入非数字值时出现报错

内容的提问来源于stack exchange,提问作者jrad09

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 11:30:17