# generaltranslation: General Translation Core SDK: formatNum URL: https://generaltranslation.com/zh/docs/core/functions/formatting/format-num.mdx --- title: formatNum description: 按区域设置惯例格式化数字的独立函数 --- ## 概述 独立的 `formatNum` 函数可按照特定区域设置的惯例格式化数字,无需 GT 实例。 它与 GT 类方法提供相同的功能,但也可单独使用。 ```typescript 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[]` | **必填** - 用于格式化的区域设置 | | `style?` | `'decimal' \| 'currency' \| 'percent' \| 'unit'` | 数字格式样式 | | `currency?` | `string` | 货币代码 (当样式为 `'currency'` 时必填) | | `minimumIntegerDigits?` | `number` | 整数部分的最少位数 (1-21) | | `minimumFractionDigits?` | `number` | 小数部分的最少位数 (0-20) | | `maximumFractionDigits?` | `number` | 小数部分的最多位数 (0-20) | | `useGrouping?` | `boolean \| 'always' \| 'auto' \| 'min2'` | 是否使用分组分隔符 | | `notation?` | `'standard' \| 'scientific' \| 'engineering' \| 'compact'` | 数字记数法格式 | ### 返回值 `string` - 按区域设置惯例格式化后的数字字符串。 *** ## 示例 ### 基本用法 ```typescript copy 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" ``` ### 货币格式 ```typescript copy // 美元 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 类方法不同,`locales` 参数是必填的 * 底层使用与 GT 类方法相同的 `Intl.NumberFormat` * 为提升重复使用相同区域设置/选项组合时的性能,结果会在内部缓存 * 如果主区域设置不受支持,则会按顺序处理回退区域设置 * 支持所有标准的 `Intl.NumberFormat` 选项 ## 后续步骤 * 查看 [`Intl.NumberFormat` 文档](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) 了解更多选项 * 关于独立的日期格式化,请参阅 [`formatDateTime`](/docs/core/functions/formatting/format-date-time) * 关于独立的消息格式化,请参阅 [`formatMessage`](/docs/core/functions/formatting/format-message) * 关于基于实例的用法,请参阅 GT 类的 [`formatNum`](/docs/core/class/methods/formatting/format-num)