简体   繁体   English

为什么[NSDecimalNumber longLongValue]返回最小值

[英]Why [NSDecimalNumber longLongValue] return min value

NSDecimalNumber *dn = [[[NSDecimalNumber alloc] initWithString:@"9223372036854775806"] autorelease];
long long llVal = [dn longLongValue]; 

why llVal is -9223372036854775808 ? 为什么llVal是-9223372036854775808?

NSDecimalNumber extends NSNumber so it supposes to handle long long type. NSDecimalNumber扩展了NSNumber,因此它假设处理long long类型。 doesn't it? 不是吗?

I believe you are running into a small base10->base2 rounding error in -longLong . 我相信你在-longLong-longLong了一个小的base10-> base2舍入错误。 I would open a defect at bugreport.apple.com. 我会在bugreport.apple.com上打开一个缺陷。 You should be able to round-trip a number within the long long range. 你应该能够在很长的距离内往返一个数字。

If you stay entirely in NSDecimalNumber , you will note that it does not suffer the rounding error. 如果你完全停留在NSDecimalNumber ,你会注意到它没有遭受舍入错误。 Here is some code that I think shows the problem very clearly: 以下是一些我认为非常清楚地显示问题的代码:

unsigned long long longlong = 9223372036854775806;
NSLog(@"longlong: %lu", longlong);
NSDecimalNumber *dn = [NSDecimalNumber decimalNumberWithMantissa:longlong exponent:0 isNegative:NO];
NSLog(@"dn-dn: %@", dn);    // Round-trips fine
NSLog(@"dn+10: %@", [dn decimalNumberByAdding:[NSDecimalNumber decimalNumberWithString:@"10"]]);    // Even does math
NSLog(@"dn-lu: %lu", [dn unsignedLongValue]); // has rounding error

2011-03-07 23:56:15.132 Untitled[16059:a0f] longlong: 9223372036854775806
2011-03-07 23:56:15.135 Untitled[16059:a0f] dn-dn: 9223372036854775806
2011-03-07 23:56:15.135 Untitled[16059:a0f] dn+10: 9223372036854775816
2011-03-07 23:56:15.136 Untitled[16059:a0f] dn-lu: 9223372036854775808

I think its because longLongValue method can be used at NSString and NSNumber and not on NSDecimalNumber . 我认为这是因为longLongValue方法可以在NSStringNSNumber上使用,而不是在NSDecimalNumber

I dont know it for sure but i think thats the reason the value of your variable is always -9223372036854775808 even if you change the string on dn 我肯定不知道它,但我认为这就是你的变量值总是-9223372036854775808的原因,即使你改变了dn上的字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM