我尝试用空格将我的double转换为字符串。现在我的数字看起来像这样1234567.54,我需要获取像这样的字符串“ 1 234 567.54”,我该如何快速完成呢?
extension StringProtocol where Self: RangeReplaceableCollection {
mutating func insert(separator: String, every n: Int) {
indices.reversed().forEach {
if $0 != startIndex { if distance(from: startIndex, to: $0) % n == 0 { insert(contentsOf: separator, at: $0) } }
}
}
func inserting(separator: String, every n: Int) -> Self {
var string = self
string.insert(separator: separator, every: n)
return string
}
}
它可以工作,但是没有我需要的
答案 0 :(得分:6)
您可以使用NumberFormatter:
let formatter = NumberFormatter()
formatter.groupingSeparator = " "
formatter.numberStyle = .decimal
let formattedNumber = formatter.string(from: 1234567.89)
print(formattedNumber)
打印:1 234 567.89