尝试将 long long 从 String 保存到 NSNumber 中
我正在尝试将一个很长的数字(作为字符串接收),例如“80182916772147201”保存到 NSNumber 中。
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterBehaviorDefault];
[item setObject:[f numberFromString:@"80182916772147201"] forKey:@"theID"];
[f release];
当我 NSLog 时,假设字符串是“80182916772147201”,我得到:
NSLog(@"%lld", [[item objectForKey:@"theID"] longLongValue]);
返回:“80182916772147200” - 请注意四舍五入的最后一位数字。
我做错了什么?
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 objectForKey:@"theID"] longLongValue]);
Returns: '80182916772147200' - Note the rounded down final digit.
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是 NSNumberFormatter 决定将该数字表示为浮点数。要强制它仅使用整数:
The problem is that
NSNumberFormatter
has decided to represent that number as a floating-point number. To force it to use integers only:你能试试这个吗?
这做出了一些合理的假设,例如 numStr 将仅包含数字,并且它包含一个“有效”的 unsigned long long 值。这种方法的一个缺点是 UTF8String 创建的内容基本上相当于 [[numStr dataUsingEncoding:NSUTF8StringEncoding] 字节],或者换句话说,每次调用都会创建 32 字节自动释放内存。对于绝大多数用途来说,这根本不成问题。
有关如何将 unsignedLongLongValue 等内容添加到 NSString 的示例,该内容既非常快又不使用自动释放的内存作为副作用,请查看我对此问题的(长)答案的结尾。特别是 rklIntValue 的示例实现,只需进行一些简单的修改即可实现 unsignedLongLongValue。
Can you try this?
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.