如何在Swift中将整数格式化为带有千位分隔符的字符串?

huangapple go评论103阅读模式
英文:

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&lt;T: BinaryInteger&gt;(_ value: T) -&gt; String {
    let numberFormatter = NumberFormatter()
    numberFormatter.numberStyle = .decimal
    numberFormatter.groupingSeparator = Locale.current.groupingSeparator ?? &quot;,&quot;
    if let formattedValue = numberFormatter.string(from: NSNumber(nonretainedObject: value)) {
        return formattedValue
    } else {
        return &quot;\(value)&quot;
    }
}

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() // &quot;123,457,890&quot;
英文:

Swift 5.5

Int64(123457890).formatted() // &quot;123,457,890&quot;

huangapple
  • 本文由 发表于 2023年7月7日 01:00:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76631067.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定