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
?
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")