尝试将 long long 从 String 保存到 NSNumber 中

发布于 2024-11-15 15:44:46 字数 497 浏览 3 评论 0原文

我正在尝试将一个很长的数字(作为字符串接收),例如“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

寻找一个思念的角度 2024-11-22 15:44:46

问题是 NSNumberFormatter 决定将该数字表示为浮点数。要强制它仅使用整数:

[f setAllowsFloats:NO];

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];
葵雨 2024-11-22 15:44:46

你能试试这个吗?

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

这做出了一些合理的假设,例如 numStr 将仅包含数字,并且它包含一个“有效”的 unsigned long long 值。这种方法的一个缺点是 UTF8String 创建的内容基本上相当于 [[numStr dataUsingEncoding:NSUTF8StringEncoding] 字节],或者换句话说,每次调用都会创建 32 字节自动释放内存。对于绝大多数用途来说,这根本不成问题。

有关如何将 unsignedLongLongValue 等内容添加到 NSString 的示例,该内容既非常快又不使用自动释放的内存作为副作用,请查看我对此问题的(长)答案的结尾。特别是 rklIntValue 的示例实现,只需进行一些简单的修改即可实现 unsignedLongLongValue。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文