'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?
Solution 1:[1]
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")
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Leo Dabus |
| Solution 2 |
