NSString 的精确浮点值
NSString *str = @"37.3336";
float f = [str floatValue];
f 为 37.3335991。
除了我自己四舍五入之外,还有没有办法从 NSString 获取精确的浮点值?
NSString *str = @"37.3336";
float f = [str floatValue];
f is 37.3335991.
Aside from rounding this myself, is there a way to get the exact float value from a NSString?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
[NSDecimalNumber DecimalNumberWithString:locale:]
。这将使数字保持十进制格式而不是二进制格式。Use
[NSDecimalNumber decimalNumberWithString:locale:]
. This will maintain the number in a decimal format rather than a binary format.不容易。 NSString 中表示的数字完全有可能没有原始浮点类型的精确表示。
如果您知道您的输入永远不会超过一定长度,并且不需要能够解析为原始浮点类型,那么您可以使用类似 NSDecimalNumber (最多 38 位数字)或者自己实现一个类似的实用程序,在其中记下小数点的位置,将数字解析为整数,并在需要打印时将小数点重新插入到正确的位置。
或者,如果您的输入长度不受限制,那么您真正可以尝试的唯一方法就是使用任意精度算术库。
请注意,使用任何这些方法,您仍然无法构造保证与您的输入完全匹配的原始浮点值。如果您需要精确的精度,那么您根本不能依赖
float
和double
。Not easily. It's entirely possible that the number represented in the
NSString
has no exact representation as a primitive floating-point type.If you know your input will never exceed a certain length, and don't need to be able to parse to a primitive floating-point type then you could use something like NSDecimalNumber (good for up to 38 digits) or implement a comparable utility yourself where you note the position of the decimal point, parse the number as an integer, and reinsert the decimal point at the correct location whenever you need to print it out.
Or if your input length is meant to be unconstrained then the only thing you can really try is using an arbitrary-precision arithmetic library.
Note that with any of these approaches, you still will not be able to construct a primitive floating-point value that is guaranteed to exactly match your input. If you need exact precision then you simply cannot rely upon
float
anddouble
.