码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-03-10 11:59:38      阅读:257      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!