开发者

Trying to save long long into NSNumber from String

I am trying to save a long long number (received as a string) such as '80182916772147201' into an NSNumber.

NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterBehaviorDefault];

[item setObject:[f numberFromString:@"80182916772147201"] forKey:@"theID"];
[f release];

When I NSLog this out, assuming the string was '80182916772147201' I get:

NSLog(@"%lld", [[item objectFor开发者_StackOverflow社区Key:@"theID"] longLongValue]); 

Returns: '80182916772147200' - Note the rounded down final digit.

What am I doing wrong?


The problem is that NSNumberFormatter has decided to represent that number as a floating-point number. To force it to use integers only:

[f setAllowsFloats:NO];


Can you try this?

NSString *numStr = [NSString stringWithFormat:@"%llu", [myNum unsignedLongLongValue]];

This makes a few reasonable assumptions such as numStr will only contain numeric digits and it contains a 'valid' unsigned long long value. A drawback to this approach is that UTF8String creates what essentially amounts to [[numStr dataUsingEncoding:NSUTF8StringEncoding] bytes], or in other words something along the lines of 32 bytes of autoreleased memory per call. For the vast majority of uses, this is no problem what-so-ever.

For an example of how to add something like unsignedLongLongValue to NSString that is both very fast and uses no autoreleased memory as a side effect, take a look at the end of my (long) answer to this SO question. Specifically the example implementation of rklIntValue, which would require only trivial modifications to implement unsignedLongLongValue.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜