Proper use and formatting of a float in Objective-C (or C)

I have an app for iPhone. I save the float value (distance) in my sqlite3 db. (The field in db is formatted for float). I can correctly store float values ​​in db. However, I cannot figure out how to derive a value from the db format and present it correctly. Here is my code for pulling a value from my db and using it:

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

[item distance] - float value. I can't get this to work. Instead, I get REALLY great value. What am I doing wrong? Any help would be greatly appreciated.

Thank you in advance for your help,

L.

+3
source share
3 answers

, -distance , , float C. . .

. , , float, , .

, - 32 ; 4 . , 0..1000000 0..1000 , , 0..1. . , .

:

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);

:

2.049999952316284180
2.450000047683715820
4200.750000000000000000
37.889999389648437500
1.200000047683715820
-1.200000047683715820

, float.

, . , ? NSDecimalNumber.

, , CoreData. .

+4

?

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

.2 , 2 .

+3

What type of distance? If this is an NSNumber instance, then I don't think the code you wrote will work, try

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

or even

float q=[[item distance] floatValue];
0
source

Source: https://habr.com/ru/post/1716859/


All Articles