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

问题描述 投票:0回答:1

我希望能够将任何整数(我目前只使用 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) // snippet does not compile.

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

swift xcode formatting foundation
1个回答
4
投票

斯威夫特5.5+

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

请注意,分隔符是根据当前区域设置自动选择的。

© www.soinside.com 2019 - 2024. All rights reserved.