@"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:
- What Every Computer Scientist Should Know About Floating-Point Arithmetic
- Floating Points on Wikipedia
- This answer on a similar question