将“NSDecimalNumber”转换为“SInt64”而不会损失精度。 (SInt64、iOS 范围内)
目前,使用字符串 @"9999999999999999"
创建的 [NSDecimalNumber longLongValue]
返回 10000000000000000
。
这意味着该类首先将其值转换为 double ,然后重新转换为 SInt64(signed long long
)
如何避免这种行为?我想获得SInt64
范围内的精确整数。
附言。 我考虑过使用 NSScanner
或 strtoll
转换为 NSString
并重新转换为 SInt64
,但我相信有更好的选择方式。但如果你确定没有其他办法,请告诉我。
Currently, [NSDecimalNumber longLongValue]
created with string @"9999999999999999"
returns 10000000000000000
.
This means the class converts it's value to double
first, and re-converts into SInt64
(signed long long
)
How to evade this behavior? I want to get precise integral number within the range of SInt64
.
PS.
I considered about converting to NSString
and re-converting into SInt64
with NSScanner
or strtoll
, but I believe there's better way. But if you sure about there's no other way, please tell me that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先:除非您确定它对性能至关重要,否则我会将其写入字符串并扫描回来。这是最简单的方法。
现在,如果您确实想这样做:
NSDecimalNumber
获取一个NSDecimal
long long
尾数的值(可能引入检查来处理太大的尾数)First: unless you're sure it's performance-critical, I'd write it into a string and scan it back. That's the easy way.
Now, if you really want to do it otherwise:
NSDecimal
from yourNSDecimalNumber
long long
value from the mantissa (possibly introduce checks to handle too-large mantissas)从 NSDecimalNumber*originalValue 开始。
令 int64_t approx = [originalValue longLongValue]。这并不准确,但非常接近。
将approx转换为NSDecimalNumber,计算originalValue -approx,取longLongValue,并添加到approx。现在你得到了正确的结果。
Start with an NSDecimalNumber* originalValue.
Let int64_t approx = [originalValue longLongValue]. This will not be exact, but quite close.
Convert approx to NSDecimalNumber, calculate originalValue - approx, take the longLongValue, and add to approx. Now you got the correct result.