【Swift】数値(Int)を3桁区切り(カンマ)で表示させる方法!NumberFormatterの使い方

この記事からわかること
- Swiftで数値(Int)を3桁区切り(カンマ)で表示させる方法
- NumberFormatterの使い方
index
[open]
\ アプリをリリースしました /
Swiftで以下のように金額や大きい数値を見やすいように3桁のカンマ区切りで表示させる方法をまとめていきます。
数値(Int)を3桁区切り(カンマ)で表示させる方法
数値(Int)を3桁区切り(カンマ)で表示させるにはNumberFormatterクラスを使用して以下のように実装可能です。
func commaSeparateThreeDigits(_ amount:Int) -> String{
let nf = NumberFormatter()
nf.numberStyle = .decimal
nf.groupingSize = 3
nf.groupingSeparator = ","
let result = nf.string(from: NSNumber(integerLiteral: amount)) ?? "\(amount)"
return result
}
細かい使い方を見ていきます。
NumberFormatterクラスとは?
NumberFormatter
とは数値とそのテキスト表現を変換する役割を持ったクラスです。
数値型であるInt
、Float
、Double
に対応しており、小数点以下の桁数なども操作することができます。
NumberFormatter.Style
公式リファレンス:NumberFormatter.Style
numberStyle
プロパティには対象となる数値のフォーマットスタイルをNumberFormatter.Style型で指定します。
設定されているロケールにも影響されるので注意してください。
NumberFormatter.Style {
case none // 整数表現
case decimal // 10進スタイル
case percent // パーセント
case scientific // 科学的なスタイル
case spellOut // 数値フォーマッタロケールで定義された言語で数字が綴られるスタイル形式
case ordinal // 序数スタイルの形式
case currency // 数値フォーマッタロケールで定義された通貨記号を使用する通貨スタイル形式
case currencyAccounting // 数値フォーマッタロケールで定義された通貨記号を使用する会計通貨スタイル形式
case currencyISOCode // 番号フォーマッタロケールで定義されたISO 4217通貨コードを使用する通貨スタイル形式
case currencyPlural // 数値フォーマッタロケールで定義された複数の宗派を使用する通貨スタイル形式
}
none
let amount = 250000
let nf = NumberFormatter()
nf.numberStyle = .decimal
let result = nf.string(from: NSNumber(integerLiteral: amount)) ?? "\(amount)"
print(result) // 250000
decimal
nf.numberStyle = .decimal
// 250,000
percent
nf.numberStyle = .percent
// 25,000,000%
scientific
nf.numberStyle = .scientific
// 2.5E5
spellOut
nf.numberStyle = .spellOut
// two hundred fifty thousand
ordinal
nf.numberStyle = .ordinal
// 250,000th
currency
nf.numberStyle = .currency
// $250,000.00
groupingSizeプロパティ
groupingSize
プロパティに任意の数値を渡すことでその桁数ごとにグループ化できます。
nf.groupingSize = 3
groupingSeparatorプロパティ
groupingSeparator
プロパティはグループごとの区切り文字を指定するプロパティです。
例えば3桁ごとにカンマで区切る米国式の表現方法の場合は先ほどのgroupingSize
とgroupingSeparator
に3
と,
を指定します。
nf.groupingSeparator = ","
まだまだ勉強中ですので間違っている点や至らぬ点がありましたら教えていただけると助かります。
ご覧いただきありがとうございました。