Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C strange decimal to long long conversion

NSLog(@"%llu\n\n", ULONG_LONG_MAX);

NSDecimalNumber *decimal = [NSDecimalNumber decimalNumberWithString:@"154550038129946620"];
NSLog(@"%@", decimal);
NSLog(@"%llu\n\n", [decimal unsignedLongLongValue]);

decimal = [NSDecimalNumber decimalNumberWithString:@"154550038129946628"];
NSLog(@"%@", decimal);
NSLog(@"%llu", [decimal unsignedLongLongValue]);

Both value are less than ULONG_LONG_MAX. But, what we see in output is:

2012-01-05 17:41:55.879 test[1276:207] 18446744073709551615

2012-01-05 17:41:55.969 test[1276:207] 154550038129946620
2012-01-05 17:41:56.095 test[1276:207] 154550038129946624

2012-01-05 17:41:56.096 test[1276:207] 154550038129946628
2012-01-05 17:41:56.096 test[1276:207] 154550038129946624

What am I doing wrong? I have no idea how to explain this behaviour.

like image 858
Alexander N. Avatar asked Jan 05 '12 13:01

Alexander N.


1 Answers

NSDecimalNumber lacks the unsignedLongLongValue method, so it inherits a default implementation from NSNumber. The only ways to get value of NSDecimalNumber are getting an NSDecimal structure, or a double. The conversion error is introduced in the process of converting NSDecimalNumber to a double.

like image 57
Sergey Kalinichenko Avatar answered Nov 04 '22 10:11

Sergey Kalinichenko