7

我有以下代码:

double d1 = 12.123456789012345;

NSString *test1 = [NSString stringWithFormat:@"%f", d1]; // string is: 12.123457

NSString *test1 = [NSString stringWithFormat:@"%g", d1]; // string is: 12.1235

如何获得与 d1 完全相同的字符串值?

4

2 回答 2

12

它可以帮助您查看 Apple 的String Format Specifiers指南。

%f  64-bit floating-point number 
%g  64-bit floating-point number (double), printed in the style of %e if the exponent is less than –4 or greater than or equal to the precision, in the style of %f otherwise

还阅读了floating point (in)accuracy,当然还有What Every Computer Scientist Should Know About Floating-Point Arithmetic

如果您真的希望字符串与双精度完全匹配,请使用NSString对其进行编码并doubleValue在您需要该值时调用。也看看NSNumberFormatter

于 2011-12-13T19:40:09.553 回答
6

怎么样

NSString *test1 = [NSString stringWithFormat:@"%.15f", d1];

或者干脆去双打

NSString *test1 = [NSString stringWithFormat:@"%lf", d1];
于 2011-12-13T19:39:15.723 回答