8

I have the following code:

double d1 = 12.123456789012345;

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

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

How do I get a string value that is exactly the same as d1?

PengOne
  • 48,188
  • 17
  • 130
  • 149
Shield
  • 123
  • 1
  • 2
  • 5

2 Answers2

13

It may help you to take a look at Apple's guide to 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

Also read up on floating point (in)accuracy, and, of course What Every Computer Scientist Should Know About Floating-Point Arithmetic.

If you really want the string to match the double exactly, then use NSString to encode it and call doubleValue when you want the value. Also take a look at NSNumberFormatter.

PengOne
  • 48,188
  • 17
  • 130
  • 149
6

How about

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

Or simply go for the double as

NSString *test1 = [NSString stringWithFormat:@"%lf", d1];
Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
A Salcedo
  • 6,378
  • 8
  • 31
  • 42