xcode 如何在Swift中将整数格式化为带有逗号分隔符的字符串?[副本]

kzmpq1sx  于 2023-08-07  发布在  Swift
关注(0)|答案(1)|浏览(109)

此问题在此处已有答案

Adding Thousand Separator to Int in Swift(7个答案)
NumberFormatter and unsigned with UInt64.max(2个答案)
上个月关门了。
我希望能够将任何整数(目前我只使用Int和UInt 16)转换为带有分隔符的String,以便对千位进行分组(如果有的话)。例如,值12,345作为输入将输出字符串“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) // snippet does not compile.


编辑:答案在这里找到https://stackoverflow.com/a/29999137/75062,但它没有显示在我的搜索.

hyrbngr7

hyrbngr71#

Swift 5.5

Int64(123457890).formatted() // "123,457,890"

字符串

相关问题