ckraider ckraider - 6 months ago 28
iOS Question

Singleton and NSNumberFormatter in Swift

Currently, I have the following code in one of my methods:

let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
formatter.currencyGroupingSeparator?
formatter.minimumFractionDigits = 2


Because I have to repeat these in various functions in different view controllers, how do I create a singleton in Swift to call for the NSNumberFormatter and avoid duplicates?

I assume that I have to create a new Swift file, but unsure of how to construct the class?

Answer
extension Double {
    var formatted:String {
        let formatter = NSNumberFormatter()
        formatter.numberStyle = .DecimalStyle
        formatter.minimumFractionDigits = 2
        formatter.maximumFractionDigits = 2
        return formatter.stringFromNumber(self) ?? ""
    }
}

100.954345.formatted    // 100.95