GuybrushThreepwood
GuybrushThreepwood

Reputation: 5616

Converting NSString to Float - Adds in Decimal Places?

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 !

Upvotes: 2

Views: 1560

Answers (2)

DBD
DBD

Reputation: 23213

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.

Upvotes: 2

James Webster
James Webster

Reputation: 32066

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:

Upvotes: 5

Related Questions