1

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 ...

Nate Lockwood
  • 3,325
  • 6
  • 28
  • 34
  • `numberFormatter.string(for: value)`. – HangarRash Jul 06 '23 at 18:56
  • @HangarRash this will suffer some issues when the value is too large https://stackoverflow.com/q/72148946/2303865 – Leo Dabus Jul 06 '23 at 19:29
  • @LeoDabus Interesting. Is the problem the use of `NumberFormatter` versus using the newer `formatted()` or is the issue with my suggestion to use the `string(for:)` method from `Formatter`? – HangarRash Jul 06 '23 at 20:03
  • 1
    I believe the issue is related to the older NumberFormatter not supporting 64 bit unsigned integers. `string(for:Any)` is declared under Formatter not NumberFormatter – Leo Dabus Jul 06 '23 at 21:20

1 Answers1

1

Swift 5.5

Int64(123457890).formatted() // "123,457,890"
soundflix
  • 928
  • 9
  • 22