NSNumberFormatter.string (from :) the maximum possible exceeded value does not lead to overflow - Swift

I convert numbers to pure English words, and I came across some very strange situations: NSNumberFormatter has a strange conclusion, less than the desired result, but the number taken as a parameter does not cause overflow.

I have the following code:

  import Foundation var numberFormatter: NumberFormatter = NumberFormatter() numberFormatter.numberStyle = .spellOut var result: String? result = numberFormatter.string(from: 999999999999999999) print(result ?? "nil") 

and that prints eighteen quadrillion fourteen trillion three hundred ninety-eight billion five hundred nine million four hundred eighty-one thousand nine hundred eighty-four , which is equivalent to 18014398509481984 < 999999999999999999 . If I try to get the words from 18014398509481984 , the result will be the one I expected, the line described above. However, if I add another 9 to 999.. , it will work with the message:

integer literal 9999999999999999999 overflows when stored in Int

Here is the Swift Sandbox Test to make the question more clear.


My actual question: Assuming the conclusion of the first attempt: 180140398509481984 is some kind of limit for numberFormatter.string(from:) , why does 999999999999999999 not lead to overflow, but simply displays this limit and 9999999999999999999 (with an additional 9) leads to overflow?

+5
source share
1 answer

9_999_999_999_999_999_999 causes Int overflow because it is greater than Int64.max equal to 9_223_372_036_854_775_807 (i.e. 0x7fffffffffffffff ).

Regarding why the format number closes at 18_014_398_509_481_984 (i.e. 2 54 0x40000000000000 ) for .spelledOut , this seems suspicious, like an error arising from 64-bit floating point representations of the cost. We cannot be sure without going through the source NSNumberFormatter and NSNumber in detail, but I suggest this because the top ceiling here, coincidentally, accurately doubles the largest integer value, which is a 64-bit floating-point type that can truly be praised.

+4
source

Source: https://habr.com/ru/post/1263824/


All Articles