0

Here is code:

NSNumber* number = [NSDecimalNumber decimalNumberWithString :@"11111111111111111"];
NSLog(@"%@ = %lld", number, [number unsignedLongLongValue]);

And I get output:

11111111111111111 = 11111111111111112

Is it known bug or I do something wrong?

UPDATE: bug reported: https://bugreport.apple.com/cgi-bin/WebObjects/RadarWeb.woa/3/wo/Stnn5Aaocknzx52c64zbN0/5.83.28.0.9

iKiR
  • 860
  • 2
  • 8
  • 20

1 Answers1

2

I believe the issue is that you are using NSNumber's -longLongValue method on an NSDecimalNumber. NSDecimalNumber stores a high-precision representation of the number internally as a decimal, but NSNumber just keeps it as an IEEE 754 double precision floating-point value. If I recall correctly, if you use the standard NSNumber superclass methods on an NSDecimalNumber, the internal number is first converted to a double, which can introduce binary floating-point artifacts like this.

As neoneye suggests, a way around this might be to use an NSString as an intermediary. For example:

NSDecimalNumber* number = [NSDecimalNumber decimalNumberWithString :@"11111111111111111"];
double number2 = [@"11111111111111111" doubleValue];

NSLog(@"%@ = %lld = %f", number, [[number descriptionWithLocale:nil] longLongValue], number2);

Will produce the result 11111111111111111 = 11111111111111111 = 11111111111111112.000000, showing both the correct result from the decimal number extraction and the error that happens when this number is temporarily stored in a double.

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
  • "If I recall correctly, if you use the standard NSNumber superclass methods on an NSDecimalNumber, the internal number is first converted to a double, which can introduce floating-point artifacts like this" Where did you get this information? It sounds strange and I hardly believe in it. In most cases we work with instance via NSNumber interface and we should not think which concrete subclass was used to construct this instance. – iKiR Jul 21 '10 at 15:09
  • @iKiR - There was some discussion here: http://stackoverflow.com/questions/2479100/cocoa-ive-discovered-what-i-think-is-a-bug-with-nsdecimalnumber , which points to Marcus' comments here: http://www.cimgf.com/2008/04/23/cocoa-tutorial-dont-be-lazy-with-nsdecimalnumber-like-me/ , but that doesn't exactly state this case. It may have been somewhere in the cocoa-dev mailing list archives that I found this, back when I ran into a similar problem. Yes, it is odd, and I think I filed a bug report on it back then. I'd recommend filing another one yourself. – Brad Larson Jul 21 '10 at 16:45
  • Thanks Brad, I filed a bug couple minutes ago: https://bugreport.apple.com/cgi-bin/WebObjects/RadarWeb.woa/3/wo/Stnn5Aaocknzx52c64zbN0/5.83.28.0.9 – iKiR Jul 22 '10 at 03:43