Adding Thousand Separator to Int in Swift

后端 未结 7 1276
长发绾君心
长发绾君心 2020-11-30 05:17

I am fairly new to Swift and having a great deal of trouble finding a way to add a space as a thousand separator.

What I am hoping to achieve is taking the result

7条回答
  •  Happy的楠姐
    2020-11-30 05:49

    I was looking for a currency format like $100,000.00 I accomplished it customizing the implementation Leo Dabus like this

    extension Formatter {
        static let withSeparator: NumberFormatter = {
            let formatter = NumberFormatter()
            formatter.numberStyle = .currency
            formatter.currencyGroupingSeparator = ","
            formatter.locale = Locale(identifier: "en_US") //for USA's currency patter
            return formatter
        }()
    }
    
    extension Numeric {
        var formattedWithSeparator: String {
            return Formatter.withSeparator.string(for: self) ?? ""
        }
    }
    

提交回复
热议问题