我有一个添加千位分隔符的问题。
我有三种类型的数字字符串。
我在 stack 的这里找到了答案。
但是我尝试使用它,未能添加千位分隔符。
你有任何建议吗?谢谢。
let str = "1000"
let string1 = "5000.000"
let string2 = "2000.0"
let convertStr = str.formattedWithSeparator //in playground, get error 「Value of type 'String' has no member 'formattedWithSeparator'」.
let convertStr1 = Float(string1)!.formattedWithSeparator //get error too.
let convertStr2 = Float(string2)!.formattedWithSeparator //get error too.
extension Formatter {
static let withSeparator: NumberFormatter = {
let formatter = NumberFormatter()
formatter.groupingSeparator = ","
formatter.numberStyle = .decimal
return formatter
}()
}
extension BinaryInteger {
var formattedWithSeparator: String {
return Formatter.withSeparator.string(for: self) ?? ""
}
}