结合 Intl.NumberFormat 实现千分位与货币符号
解读
国内一线/二线前端面试中,「国际化」已从加分项变成刚需。面试官抛出此题,表面考「千分位+货币符号」的格式化,实则同时考察:
- 是否知道原生 Intl API,避免自己写正则/手写循环;
- 能否在 React 组件内优雅封装,兼顾 SSR、性能与可维护性;
- 是否理解 locale 与 currency 参数对人民币、美元、欧元等不同币种的差异;
- 是否考虑运行时性能(避免每次 render new Intl.NumberFormat)与缓存策略;
- 是否具备异常边界思维(非法 currency、旧浏览器 Polyfill、服务端水合不一致)。
知识点
- Intl.NumberFormat 构造器:locale 决定千分位分隔符与小数点符号,currency 决定货币符号位置与符号本身;
- 浏览器支持度:Chrome 24+、Edge、Safari 10+、Firefox 29+;国内仍需兼容 Android 5 WebView 时须带 Polyfill(formatjs/intl-numberformat);
- 性能陷阱:在 render 里直接 new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY' }) 会每次创建新对象,触发垃圾回收;
- React 封装模式:Context + Hook(useNumberFormatter)或单例 Map 缓存;
- SSR 水合:Node 端默认不带 ICU 数据,需安装 full-icu 或使用 Polyfill,否则格式化结果与客户端不一致导致水合错误;
- 人民币格式细节:locale='zh-CN' 时,currency='CNY' 输出「¥1,234.56」;若要求「CN¥」或「RMB」符号,需自定义 currencyDisplay;
- 可访问性:金额文本需附带 aria-label 供读屏软件识别,避免朗读「¥」为「美元符号」;
- 测试策略:Jest 环境无 ICU,需 mock 或提前注入 Polyfill,保证快照稳定。
答案
// formatter.ts
import { memoize } from 'lodash-es';
export type Currency = 'CNY' | 'USD' | 'EUR';
const cache = new Map<string, Intl.NumberFormat>();
export const getFormatter = memoize(
(locale: string, currency: Currency) => {
const key = `${locale}-${currency}`;
if (!cache.has(key)) {
cache.set(
key,
new Intl.NumberFormat(locale, {
style: 'currency',
currency,
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})
);
}
return cache.get(key)!;
},
(locale, currency) => `${locale}-${currency}`
);
// useCurrency.ts
import { useMemo } from 'react';
import { getFormatter, Currency } from './formatter';
export function useCurrency(
value: number,
currency: Currency = 'CNY',
locale: string = 'zh-CN'
) {
return useMemo(() => {
if (Number.isNaN(value)) return '--';
const formatter = getFormatter(locale, currency);
return formatter.format(value);
}, [value, currency, locale]);
}
// Currency.tsx
import React from 'react';
import { useCurrency } from './useCurrency';
interface Props {
value: number;
currency?: 'CNY' | 'USD' | 'EUR';
locale?: string;
className?: string;
}
export const Currency: React.FC<Props> = ({ value, currency, locale, className }) => {
const text = useCurrency(value, currency, locale);
return (
<span className={className} aria-label={`金额: ${text}`}>
{text}
</span>
);
};
// 使用示例
<Currency value={1234567.8} currency="CNY" /> // ¥1,234,567.80
<Currency value={1234567.8} currency="USD" locale="en-US" /> // $1,234,567.80
亮点说明:
- 使用 Map + lodash.memoize 双保险缓存,保证同 locale+currency 只实例化一次;
- Hook 返回格式化字符串,组件层仅做展示,职责单一;
- 防御 NaN 与边界值,避免运行时抛错;
- aria-label 提升无障碍体验;
- 文件拆分方便单元测试:可针对 formatter.ts 做 Jest 快照测试,无需渲染 React 组件。
拓展思考
- 动态切换 locale:在 React 18 的 useTransition 下,可结合 i18next 或 next-intl,实现「中英双语+币种」一键切换,同时保持页面不闪;
- 大数据列表优化:虚拟滚动表格中,每行都调用格式化可能成为瓶颈,可提前将数字映射为字符串,或使用 Web Worker 批量转换;
- 精度问题:金融场景下 0.1+0.2≠0.3,需先使用 decimal.js 把浮点转为整数分,再交给 Intl.NumberFormat,避免显示「¥0.30」却实际少分;
- 自定义符号:若产品要求「RMB 1,234.56」而非「¥」,可扩展 currencyDisplay:'code' 或 'name',甚至通过 formatToParts 手动拼接;
- 合规与审计:国内电商需符合《人民币图样使用管理办法》,线上展示「¥」不受限,但离线打印小票需用「CNY」字样,封装层可通过环境变量自动切换;
- SSR 体积优化:Next.js 边缘函数场景,full-icu 会增加 6 MB,可按请求动态加载 Polyfill,或利用 CDN 边缘缓存格式化结果,减少冷启动时间。