首页 > 其他 > 详细

NSString 转换 float 的精度问题, 换double类型可以解决

时间:2015-03-10 11:59:23      阅读:2559      评论:0      收藏:0      [点我收藏+]

@"0.01" 转换成float时, 经常会变成  0.009999799 这种形式, 因为float类型无法精准保存, 系统会选一个接近的值来代替.

而double类型则可以有更好的精度.

技术分享

 

 

 

http://stackoverflow.com/questions/9328260/converting-nsstring-to-float-adds-in-decimal-places

Your issue seems to be that you don‘t understand how floats are stored in memory and don‘t know that floats aren‘t precise.

Exact values often can‘t be stored and so the system picks the closest number it can to represent it. If you look carefully, you can see that each of the outputted numbers is very close to your inputted values.

For better accuracy, try using double instead. Double does encounter the same problems, but with better precision. Floats have about 6 significant digits; doubles have more than twice that.Source

Here are some other StackOverflow answers and external articles you should read:

NSString 转换 float 的精度问题, 换double类型可以解决

原文:http://www.cnblogs.com/willbin/p/4325502.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!