英文:
How is an integer formatted to a String with comma separators for thousands in Swift?
问题
我想能够将任何整数,目前我只使用 Int 和 UInt16,转换为带有千位分隔符的字符串。例如,输入值 12345 会输出字符串 "12,345"。
我找到了这个解决方案,但它失败了,返回 "12345"。
import Foundation
func readable<T: BinaryInteger>(_ value: T) -> String {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.groupingSeparator = Locale.current.groupingSeparator ?? ","
if let formattedValue = numberFormatter.string(from: NSNumber(nonretainedObject: value)) {
return formattedValue
} else {
return "\(value)"
}
}
我首先找到了关于 NSNumber 的参数的变化,但它无法编译,所以我怀疑 NSNumber 的参数不正确。
如何修复这个问题?
NSNumber(value: value) // 片段无法编译。
编辑:答案在这里找到了 https://stackoverflow.com/a/29999137/75062 但它在我的搜索结果中没有显示...
英文:
I want to be able to convert any integer, I'm only using Int and UInt16 at the moment, into a String with a separator to group the thousands, if any. For example the value 12345 as input would output the string "12,345".
I found this solution but it fails, returning "12345".
import Foundation
func readable<T: BinaryInteger>(_ value: T) -> String {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.groupingSeparator = Locale.current.groupingSeparator ?? ","
if let formattedValue = numberFormatter.string(from: NSNumber(nonretainedObject: value)) {
return formattedValue
} else {
return "\(value)"
}
}
I had first found a variation of the argument for NSNumber but that does not compile so I suspect that the argument for NSNumber is not correct.
How do I fix this?
NSNumber(value: value) // snippet does not compile.
Edit: The answer is found here
https://stackoverflow.com/a/29999137/75062
but it didn't show on my searches ...
答案1
得分: 1
Int64(123457890).formatted() // "123,457,890"
英文:
Swift 5.5
Int64(123457890).formatted() // "123,457,890"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论