iOSエンジニアのつぶやき

毎朝8:30に iOS 関連の技術について1つぶやいています。まれに釣りについてつぶやく可能性があります。

Swift で数値を3文字区切りの文字列に変換する【コピペ 用】

Swift で数値をカンマで区切って表現したい時などには下記の Extension Property が使用できます。

extension Int {
    var withCommaString: String {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        formatter.groupingSeparator = ","
        formatter.groupingSize = 3

        return formatter.string(from: NSNumber(value: self)) ?? "\(self)"
    }
}

NumberFormatter.Style

NumberFormatter.Style を使用するとデバイスのローカル言語に合わせて数値をフォーマットしてくれます。下記が公式ドキュメントにも記載してある US, France, China の例です。

Style en_US Locale fr_FR Locale zh_CN Locale
.none 1235 1235 1235
.decimal 1,234.568 1 234,568 1,234.568
.percent 12% 12 % 12%
.scientific 1.2345678E3 1,2345678E3 1.2345678E3
.spellOut one hundred twenty-three cent vingt-trois 一百二十三
.ordinal 3rd 3e 第3
.currency $1,234.57 1 234,57 € ¥1,234.57
.currencyAccounting ($1,234.57) (1 234,57 €) (¥1,234.57)
.currencyISOCode USD1,234.57 1 234,57 EUR CNY1,234.57
.currencyPlural 1,234.57 US dollars 1 234,57 euros 1,234.57人民币

https://developer.apple.com/documentation/foundation/numberformatter/style

その他の記事

yamato8010.hatenablog.com

yamato8010.hatenablog.com

yamato8010.hatenablog.com