Search code examples
swiftnumbersresolution

Swift- NumberFormatter


Numbeformatter

extension Double {
    var formatedPrice: String? {
        let formatter = NumberFormatter()
        formatter.locale = Locale(identifier: "ja_JP")
        formatter.numberStyle = .decimal
        if let formatedString = formatter.string(from: self as NSNumber) {
            return formatedString 
        } 
        return nil
    }
}

print(Double(12_121_212_121_212_121_212).formatedPrice)

and this is result:

Optional("¥12,121,212,121,212,100,000")

The number is rounded if too big. Does anyone know how to solve this?


Solution

  • If you need more than 15 digits precision you can use Swift Decimal type. Btw you should use its string initializer when creating your Decimal value and create a static NumberFormatter to avoid creating a new one every time you call this property:

    extension Decimal {
        var formatedPrice: String? {
            Decimal.formatter.string(for: self)
        }
        static let formatter: NumberFormatter = {
            let formatter = NumberFormatter()
            formatter.locale = Locale(identifier: "ja_JP")
            formatter.numberStyle = .currency
            return formatter
        }()
    }
    

    Usage:

    Decimal(string: "12121212121212121987")?.formatedPrice   // "¥12,121,212,121,212,121,987"