Test case:
NSLog(@"%f", M_PI);
NSLog(@"%@", [NSString stringWithFormat:@"%f", M_PI]);
NSLog(@"%@", [NSNumber numberWithDouble:M_PI]);
Results:
3.141593
3.141593
3.141592653589793
Conclusions:
1) Printing via NSLog() or [NSString stringWithFormat] provide a very low precision...
2) Printing via [NSNumber numberWithDouble] provides a better precision...
I would have expected to get a result much closer to the original value: 3.14159265358979323846264338327950288 (as defined in math.h)
Any clues?
The first two lines round to 6 decimals because that's the default rounding length for
printf
inherited from C.The third line displays the data with the maximum useful precision - an IEEE 754 64bit floating-point number has slightly less than 16 decimal digits of precision, so all those digits of the literal in
math.h
are pointless (perhaps they can be seen as future-proofing against a possible future redefinition in a format with more precision).Try this, this work for me
NSLog(@"%@",[NSString stringWithFormat:@"%f",distance]);
a little more precision
Try this:
Maybe a bit late as of an answer but someone might stumble upon these problems:
You should use long double with a maximum formatting of 20 digits @.20Lg. The long doubles are 80-bit floating points, so you will not get a better precision than that. Be aware also that as of XCode 4.3.2 the constants are not in long double notation, even if the many digits suggest an uberlong double ;-)
the results are: