数字格式化
想要观看视频吗?
数字的格式化会根据用户的区域设置有所不同,可能包括不同的规则,例如:
- 小数分隔符(例如
en-US中的 “12.3” 与de-DE中的 “12,3”) - 位数分组(例如
en-US中的 “120,000” 与hi-IN中的 “1,20,000”) - 货币符号位置(例如
de-DE中的 “12 €” 与de-AT中的 ”€ 12”)
通过使用 next-intl 提供的格式化功能,您可以适应这些差异,确保在您的 Next.js 应用中为所有用户准确显示数字。
格式化普通数字
当你格式化独立的数字(不作为消息的一部分)时,可以使用一个单独的 hook:
import {useFormatter} from 'next-intl';
function Component() {
const format = useFormatter();
// 渲染 "$499.90"
format.number(499.9, {style: 'currency', currency: 'USD'});
}请参阅 MDN 文档中的 NumberFormat 了解可传递给 number 函数的选项,或者尝试使用 交互式浏览器 探索 Intl.NumberFormat。
如果你配置了全局格式,可以通过传递名称作为第二个参数来引用它们:
// 使用全局格式
format.number(499.9, 'precise');
// 可选地覆盖一些选项
format.number(499.9, 'price', {currency: 'USD'});消息中的数字
数字可以通过 ICU 语法嵌入消息中。
en.json
{
"basic": "基础格式化:{value, number}",
"percentage": "以百分比显示:{value, number, percent}",
"custom": "最多 2 位小数:{value, number, ::.##}"
}注意开头的 :: 用于表示应使用 skeleton。想了解更多,请参阅 ICU 文档中的数字 skeleton。
这些格式默认支持:currency 和 percent。
💡
如果您与翻译人员合作,使用支持 ICU 数字语法的编辑器可能对他们有所帮助(例如 Crowdin 编辑器)。
自定义数字格式
要在消息中使用自定义格式,您可以提供可通过名称引用的格式化程序。
en.json
{
"price": "该产品价格为 {price, number, currency}"
}t(
'price',
{price: 32000.99},
{
number: {
currency: {
style: 'currency',
currency: 'EUR'
}
}
}
);💡
若想在多个组件间复用数字格式,您可以配置全局格式。