3
0

More than 3 years have passed since last update.

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

Posted at

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人民币

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0