Leachy Peachy
Leachy Peachy

Reputation: 1132

Proper Usage and Formatting of a Float in Objective-C (or C)

I have an iPhone app. I am storing a float value, (distance), in my sqlite3 db. (The field in the db is formatted to float) I am able to store float values correctly in the db no problem. However, I can't seem to figure out how to pull the value back out of the db the format and present it correctly. Here is my code for pulling the value out of my db and using it:

NSString *itemDistance = [NSString stringWithFormat:@"%f",[item distance]];
float questionDistance = [itemDistance floatValue];

[item distance] is a float value. I can't get this to work. I get a REALLY long value instead. What am I doing wrong? Any help would be greatly appreciated.

Thank you in advance for your help,

L.

Upvotes: 3

Views: 2855

Answers (3)

KenO
KenO

Reputation: 31

why go round in circles?

NSString *itemDistance = [NSString stringWithFormat:@"%.2f",[item distance]];
float questionDistance = [itemDistance floatValue];

Where the .2 is saying I want 2 decimal places.

Upvotes: 3

bbum
bbum

Reputation: 162712

Assuming your -distance method is returning the right value, then this sounds like basic misunderstanding of how floats work in C. Common mistake. Every developer falls into this trap at least once.

Floating point numbers can actually only represent a fairly limited number of values. Specifically, unless you happen to choose a value that is exactly representable as a float, you'll get the nearest value, which will often have many decimal places of data.

The reason for this is because a float is only 32 bits; 4 bytes. Now, how many numbers with decimal points are there between 0..1000000 or 0..1000 or, even, 0..1. Infinite. Floats implement a very finite subset of possible numeric values and do so in a way where the resulting possible values may have many decimal places.

Consider:

printf("%5.18f\n", (float) 2.05);
printf("%5.18f\n", (float) 2.45);
printf("%5.18f\n", (float) 4200.75);
printf("%5.18f\n", (float) 37.89);
printf("%5.18f\n", (float) 1.2);
printf("%5.18f\n", (float) -1.2);

This prints:

2.049999952316284180
2.450000047683715820
4200.750000000000000000
37.889999389648437500
1.200000047683715820
-1.200000047683715820

Those values are as close to the values in the bit of code that a float could represent.

If you need more precision, use a double. More precision than that? Use NSDecimalNumber.

And, if you can, use CoreData. It makes managing this kind of thing a bit more straightforward.

Upvotes: 4

Daniel
Daniel

Reputation: 22395

Whats the type of of distance? If it is an instance of NSNumber then I dont think the code you wrote will work, try

NSString *itemDistance = [[item distance] stringValue];
float questionDistance = [itemDistance floatValue];

or even

float q=[[item distance] floatValue];

Upvotes: 0

Related Questions