Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

iphone - How to print a double with full precision on iOS?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...