Property List inaccurate (floats)


For challenge 30 I am writing different data types to a property list. But the corresponding float property differs from what it’s supposed to be. Can someone please explain that to me or give a better - more reliable - solution? I suppose it’s got more to do with floats than property lists per se. Thanks a lot.

NSMutableArray *someProperties = [[NSMutableArray alloc]init];
NSNumber *someFloat = [NSNumber numberWithFloat:10.37];
[someProperties addObject:someFloat];
// …adding other types…
// writing properties to file
[someProperties writeToFile:@"/tmp/props.plist" atomically:YES];

When I checked the written XML file I encountered a funny inaccuracy:
Hallo World


It is really just how the compiler reads it. A float is 8-bytes. When we print a float using NSLog we specify the number of digits that it will round up to (such as %.2f or %.4f). Your application doesn’t format the float so the compiler adds numbers behind it to fill the 7 bytes of the value (remember, 1 byte is used for the sign unless it is an unsigned float). This is warned within one of the chapters in the first section of the book. Can’t say which for sure. WIll look up and get back to you.

I am still a bit confused with it. I understand this much, but I still don’t see why it adds random numbers behind so if anyone can explain better jump in :slight_smile:


The fractional part of a real number R, such as 10.37, is represented as a finite sum of the terms of the form k * (1/2^n).

FracPart (R) = sum (k * (1/2^n)), where k = {0, 1} and n = 1, 2, 3, ...

For 10.37:

FracPart (10.37) = 0 * (1/2) + 1 * (1/2^2) + 1 * (1/2^3) + ...

That’s why some real numbers may print differently from what you may expect.