# General Translation Platform: formatCurrency URL: https://generaltranslation.com/zh/docs/platform/core/reference/utility-functions/formatting/format-currency.mdx --- title: formatCurrency description: 无需 GT 实例,即可按区域设置格式化货币值。formatCurrency 的 API 参考。 --- [`formatCurrency`](/docs/platform/core/reference/gt-class-methods/formatting/format-currency) 是 General Translation core library 提供的一个独立实用函数,用于将数值格式化为本地化货币字符串。它对内置的 `Intl.NumberFormat` API 进行了封装,并使用货币 `style`。 ## Overview [#overview] 直接从 `generaltranslation` 导入 `formatCurrency`,调用时传入一个值、货币代码和选项对象即可。它不需要 API Key,也不需要 [GT](/docs/platform/core/reference/gt-class/constructor) 实例。若要使用会继承实例区域设置的实例格式化方式,请改用 [`GT`](/docs/platform/core/reference/gt-class/constructor) 实例上的 [`formatCurrency`](/docs/platform/core/reference/gt-class-methods/formatting/format-currency) 方法。 ```typescript import { formatCurrency } from 'generaltranslation'; const price = formatCurrency(1234.56, 'EUR', { locales: ['de-DE'] }); // "1.234,56 €" ``` 签名: ```typescript formatCurrency( value: number, currency: string, options?: { locales?: string | string[] } & Intl.NumberFormatOptions ): string ``` ## 工作方式 [#how-it-works] * **底层 API。** 使用与 GT 类方法相同的 [`Intl.NumberFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat),并将 `style` 设为 `'currency'`。 * **区域设置解析。** 省略 `locales` 时,会回退到库的默认区域设置 `en`。 * **符号位置。** 货币符号、分组分隔符和小数格式都遵循解析后的区域设置。 ## 参数 [#parameters] | 参数 | 描述 | 类型 | 可选 | 默认值 | | ----------------------- | ------------------------------- | ------------------------------------------------------------- | -- | ---- | | [`value`](#value) | 要格式化的数值。 | `number` | 否 | — | | [`currency`](#currency) | ISO 4217 货币代码,例如 `USD` 或 `EUR`。 | `string` | 否 | — | | [`options`](#options) | 格式化配置,包括目标区域设置。 | `{ locales?: string \| string[] } & Intl.NumberFormatOptions` | 是 | `{}` | ### `value` [#value] **类型** `number` · **必填** 要格式化的数值。 ### `currency` [#currency] **类型** `string` · **必填** ISO 4217 货币代码,例如 `USD`、`EUR` 或 `JPY`。 ### `options` [#options] **Type** `{ locales?: string | string[] } & Intl.NumberFormatOptions` · **可选** · **默认值** `{}` 格式化配置: | 属性 | 描述 | Type | 可选 | 默认值 | | --------- | --------------- | -------------------- | -- | ------------ | | `locales` | 用于格式化的区域设置。 | `string \| string[]` | 是 | `en` | | `style` | 数字格式样式;默认为货币格式。 | `string` | 是 | `'currency'` | ## 返回值 [#returns] **类型** `string` 格式化后的本地化货币字符串值。 ## 示例 [#examples] ```typescript import { formatCurrency } from 'generaltranslation'; // 美元 console.log(formatCurrency(1234.56, 'USD', { locales: 'en-US' })); // Output: "$1,234.56" // 欧元,德语区域设置 console.log(formatCurrency(1234.56, 'EUR', { locales: 'de-DE' })); // Output: "1.234,56 €" // 日元(无小数位) console.log(formatCurrency(1234, 'JPY', { locales: 'ja-JP' })); // Output: "¥1,234" ``` ## 注意事项 [#notes] * 请始终显式传入 `locales` 值,以确保输出正确且结果可预测。 * 可将任意 `Intl.NumberFormatOptions` (例如 `minimumFractionDigits`) 与 `locales` 一并传入,以进一步微调输出结果。