1

I'm trying to create a string representing UInt64.max using NumberFormatter. Here's the code:

let formatter = NumberFormatter()
    
formatter.usesGroupingSeparator = true
formatter.numberStyle = .decimal
formatter.positiveFormat = "# ##0.#########"
formatter.maximumSignificantDigits = 20
formatter.usesSignificantDigits = false
formatter.maximumFractionDigits = 20
formatter.minimumFractionDigits = 0
formatter.alwaysShowsDecimalSeparator = false
// formatter.roundingMode = .halfUp
let text1 = formatter.string(for: NSNumber(value: Int64.max))
let text2 = formatter.string(for: NSNumber(value: UInt64.max))

print(text1)
print(text2)

which prints:

Optional("9,223,372,036,854,780,000")
Optional("-1")

but should print

Optional("9223372036854775807")
Optional("18,446,744,073,709,551,615")

It looks like NSNumber is rounding Int64 and isn't taking the UIn64. The obj-c version of NSNumberFormatter works fine.

Am I missing something or is there a problem with NumberFormatter?

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Phantom59
  • 947
  • 1
  • 8
  • 19

2 Answers2

1

You can use the new formatted Generic Instance Method and specify number style:

iOS15+ • Xcode 13

let decimal1 = Decimal(Int64.max)
let decimal2 = Decimal(UInt64.max)

let text1 = decimal1.formatted(.number)
let text2 = decimal2.formatted(.number)

print(text1)
print(text2)

This will print

9,223,372,036,854,775,807
18,446,744,073,709,551,615

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • Have admit its new to me but found some details that make it worth wild looking into it. [More details here.](https://developer.apple.com/documentation/swift/sequence/3767271-formatted) Thank! – Phantom59 May 09 '22 at 01:05
  • @Phantom59 Sorry I posted the wrong link. Unfortunately the documentation is really poor. https://developer.apple.com/documentation/foundation/decimal/3796456-formatted – Leo Dabus May 09 '22 at 01:59
0

After some tinkering, found a solution:

let text2 = formatter.string(for: Decimal(UInt64.max))
print(text2)

This prints Optional("18,446,744,073,709,600,000")

Related thread

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Suyash Medhavi
  • 1,135
  • 6
  • 18