Double roundtripping for text and return

advertisements

Using Cocoa or basic c, how can I convert a double to a string representation and then convert it back to the exact same double. Readability is not important, only accuracy. For example, will this work:
double a,b;
a=some value;
b=[[[NSNumber numberWithDouble:a] stringValue] doubleValue];


[EDIT] Actually there is a way to do this in C99 -- use the %a format specifier. This prints out a double in hexadecimal scientific notation, so there is no loss of precision. The result is exact. Example:

double d1 = 3.14159;
char str[64];
sprintf(str, "%a", d1);
// str is now something like "0x1.921f9f01b866ep+1"
...
double d2;
sscanf(str, "%la", &d2);
assert(d2 == d1);

Original answer below:


Most double-to-string conversions can't guarantee that. You can try printing out the double to a very high precision (a double can store about 16 decimal digits), but there's still a small chance of floating-point error:

// Not guaranteed to work:
double d = ...;
char str[64];
sprintf(str, "%.30g", d);
...
double d2;
sscanf(str, "%g", &d2);

This will work to a very high degree of precision, but it still may have an error of a few ULPs (units in the last place).

What are you doing that requires you to produce a 100% exactly reproducible value while using a string? I strongly suggest you reconsider what you're trying to do. If your really need an exact conversion, just store the double as 8 bytes in binary. If it needs to be stored in a printable format, convert the binary data into hex (16 bytes) or base 64.