Utility FunctionsFormatting
formatNum
locale の規則に従って数値を整形するスタンドアロン関数
概要
スタンドアロンの formatNum 関数は、GT インスタンスなしで、locale に固有の慣習に従って数値を整形します。
GT クラスのメソッドと同等の機能を提供しますが、単体で使用できます。
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[] } | 必須の対応ロケールを含む書式設定 | 
NumberFormatOptions
| Name | Type | Description | 
|---|---|---|
| locales | string | string[] | 必須 - 書式設定に使用する対応ロケール | 
| 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 クラスのメソッドと異なり、localesパラメータは必須です
- GT クラスのメソッドと同じ基盤の Intl.NumberFormatを使用します
- 同じ locale/options の組み合わせが繰り返される場合に備え、結果は内部でキャッシュされます
- 主要な locale がサポートされていない場合、フォールバックの locale は指定順に処理されます
- すべての標準的な Intl.NumberFormatの options に対応しています
次のステップ
- さらに多くの options については、Intl.NumberFormatのドキュメントをご確認ください
- 単体の日時フォーマットについては、formatDateTimeを参照してください
- 単体のメッセージフォーマットについては、formatMessageを参照してください
- インスタンスベースでの利用については、GT クラスのformatNumを参照してください
- 通貨に特化したフォーマットについては、formatCurrencyを参照してください
このガイドはどうでしたか?

