【发布时间】:2018-11-26 05:56:27
【问题描述】:
我有一个关于添加千位分隔符的问题。
我有三种类型的数字字符串。
我在堆栈中找到答案here.
但是我尝试使用它,并没有添加千位分隔符。
对我有什么想法吗?谢谢。
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) ?? ""
}
}
【问题讨论】:
-
为什么要减去我的问题?
-
如果它解决了问题,您愿意接受答案吗?这将帮助其他人快速找出答案。