2011-12-13 49 views
6

我有以下代碼:Objective-C的stringValue的雙重

double d1 = 12.123456789; 

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

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

我如何獲得一個字符串值,它是作爲D1一模一樣?

回答

6

如何

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

或者乾脆去兼作

NSString *test1 = [NSString stringWithFormat:@"%lf", d1]; 
+0

`%d`是一個整數 – PengOne 2011-12-13 19:44:12

11

它可以幫助你看看蘋果的指導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的。

如果您確實希望字符串完全匹配double,請使用NSString對其進行編碼,並在需要時調用doubleValue。也看看NSNumberFormatter