Converting NSString to Float - Adds in Decimal Places?

一世执手 提交于 2019-12-11 01:37:23

问题


I am parsing some vertice information from an XML file which reads as follows (partial extract) :

21081.7 23447.6 2781.62 24207.4 18697.3 -2196.96

I save the string as an NSString and then convert to a float value (which I will later feed into OpenGL ES)

NSString * xPoint = [finishedParsingArray objectAtIndex:baseIndex];
                 NSLog(@"xPoiint is %@", xPoint);

                 float x = [xPoint floatValue];

The problem is that float x changes the values as follows :

21081.699219, 23447.599609, 2781.620117, 24207.400391, 18697.300781, -2196.959961

As you can see, it is changing the number of decimal places (not sure how it is doing this - must be hidden formatting in the xml file ?)

My question is how can I store the float to match the original number in the NSString / XML file to the same number of decimal places ?

Thanks in advance !


回答1:


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



回答2:


All primitives which store floating point numbers have an accuracy issue. Most of the time it's so small it doesn't matter, but sometimes it's vital.

When it's important to keep the exact number, I would suggest using NSDecimalNumber.



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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!