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のガイドを参照すると役立つ場合があります。

%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

また、浮動小数点の(不)精度、そしてもちろん、すべてのコンピューター科学者が浮動小数点演算について知っておくべきことについても読んでください。

文字列をdoubleと完全に一致させたい場合は、を使用して文字列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 に答える