6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Swift3] Intをカンマ編集するextension&その逆

Last updated at Posted at 2017-01-27

今更ながらのネタですが…
もっとエレガントな手法をコメントいただけるかも?と期待して書きます。

※いただいたコメントを参考にブラッシュアップしてみました。(2017/1/28)

環境

Items Version
Xcode 8.2
Swift 3.0.2

定義

/// Int拡張
extension Int {
    /// カンマ付け
    var withComma: String {
        let decimalFormatter = DecimalFormatter()
        guard let s = decimalFormatter.string(from: self as NSNumber) else {
            fatalError()
        }
        return s
    }
}

/// String拡張
extension String {
    /// カンマ区切り数字のカンマどり
    var noComma: Int {
        if self.characters.count == 0 {
            return 0
        }
        let decimalFormatter = DecimalFormatter()
        guard let i = decimalFormatter.number(from: self) else {
            preconditionFailure("NumberFormatter.number method failure!")
        }
        return Int(i)
    }
}

/// カンマ編集制御用NumberFormatter拡張クラス
class DecimalFormatter: NumberFormatter {
    override init() {
        super.init()
        self.locale = Locale(identifier: "ja_JP")
        self.numberStyle = .decimal
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

呼び出し

let s: String = (1234567).withComma         //"1,234,567"
let i: Int = s.noComma                      //1234567
let i2: Int = "123,456x".noComma            //Error

(参考)ブラッシュアップ前

/// Int拡張
extension Int {
    /// カンマ付け
    var commmaDecStr: String {
        let decimalFormatter = NumberFormatter()
        decimalFormatter.numberStyle = NumberFormatter.Style.decimal
        decimalFormatter.groupingSeparator = ","
        decimalFormatter.groupingSize = 3
        
        return decimalFormatter.string(from: self as NSNumber)!
    }
}

/// String拡張
extension String {
    /// カンマ区切り数字のカンマどり
    var delCommmaFromDecStr: String {
        if self.characters.count > 0 {
            return self.replacingOccurrences(of: ",", with: "")
        } else {
            return "0"
        }
    }
}

I Love Swift!!:heart_eyes:

6
6
2

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
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?