我有以下代码:
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完全相同的字符串值?
答案 0 :(得分: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
。
答案 1 :(得分:6)
怎么样
NSString *test1 = [NSString stringWithFormat:@"%.15f", d1];
或者只是选择双击
NSString *test1 = [NSString stringWithFormat:@"%lf", d1];