Utility FunctionsFormatting
formatNum
按照 locale 约定格式化数字的独立函数
概述
独立的 formatNum 函数可按特定 locale 的约定格式化数字,无需依赖 GT 实例。
它提供与 GT class 中对应方法相同的功能,但可单独使用。
import { formatNum } from 'generaltranslation';
const formatted = formatNum(1234.56, {
  locales: 'de-DE',
  style: 'currency',
  currency: 'EUR'
});
// 返回:"1.234,56 €"参考资料
参数
| 名称 | 类型 | 描述 | 
|---|---|---|
| number | number | 要格式化的数值 | 
| options | NumberFormatOptions & { locales: string | string[] } | 含必填 locales 的格式化配置 | 
NumberFormatOptions
| 名称 | 类型 | 描述 | 
|---|---|---|
| locales | string | string[] | 必填 — 用于格式化的 locales | 
| style? | 'decimal' | 'currency' | 'percent' | 'unit' | 数字格式样式 | 
| currency? | string | 货币代码(当 style 为 'currency' 时必填) | 
| minimumIntegerDigits? | number | 最少整数位数(1-21) | 
| minimumFractionDigits? | number | 最少小数位数(0-20) | 
| maximumFractionDigits? | number | 最多小数位数(0-20) | 
| useGrouping? | boolean | 'always' | 'auto' | 'min2' | 是否使用分组符号 | 
| notation? | 'standard' | 'scientific' | 'engineering' | 'compact' | 数字记数法 | 
返回值
string - 按照 locale 约定格式化后的数字。
示例
基本用法
import { formatNum } from 'generaltranslation';
// 基本数字格式化
console.log(formatNum(1234.567, { locales: 'en-US' }));
// 输出:"1,234.567"
// 德语格式化
console.log(formatNum(1234.567, { locales: 'de-DE' }));
// 输出:"1.234,567"货币格式
// 美元
console.log(formatNum(1234.56, {
  locales: 'en-US',
  style: 'currency',
  currency: 'USD'
}));
// 输出: "$1,234.56"
// 德国地区的欧元
console.log(formatNum(1234.56, {
  locales: 'de-DE',
  style: 'currency',
  currency: 'EUR'
}));
// 输出: "1.234,56 €"
// 日元
console.log(formatNum(1234.56, {
  locales: 'ja-JP',
  style: 'currency',
  currency: 'JPY'
}));
// 输出: "¥1,235"说明
- 与 GT class 方法不同,locales参数是必填项
- 使用与 GT class 方法相同的底层 Intl.NumberFormat
- 对重复的 locale/options 组合会在内部缓存以提升性能
- 如果主要 locale 不受支持,将按顺序处理 fallback locale
- 支持所有标准的 Intl.NumberFormatoptions
后续步骤
- 查看 Intl.NumberFormat文档,了解更多 options
- 参见 formatDateTime获取独立的日期格式化
- 参见 formatMessage获取独立的消息格式化
- 参见 GT class formatNum了解基于实例的用法
- 参见 formatCurrency获取专用的货币格式化
这份指南怎么样?

