JavaScript/React加拿大法语CAD货币格式化功能修正求助
问题修正方案
核心问题分析
- 参数类型错误:调用
formatPrice时,你先把数字转成了字符串(Number(...).toLocaleString()),但formatPrice需要的是数字类型,字符串调用toLocaleString的逻辑完全不符合预期,直接导致格式失效。 - Locale参数不精准:只用
"fr"或"en"无法确保是加拿大地区的格式,必须指定"fr-CA"(加拿大法语)和"en-CA"(加拿大英语)才能生成目标格式。 - 重复添加货币符号:
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
相关产品推荐
相关产品推荐

