NumberFormatter and unsigned with UInt64.max

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?

2 answers

  • answered 2022-05-07 11:28 Suyash Medhavi

    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

  • answered 2022-05-07 23:40 Leo Dabus

    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

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum