Convert Double to String C++

Convert double/float to string

The only exact solution is to perform arbitrary-precision decimal arithmetic for the base conversion, since the exact value can be very long - for 80-bit long double, up to about 10000 decimal places. Fortunately it's "only" up to about 700 places or so for IEEE double.

Rather than working with individual decimal digits, it's helpful to instead work base-1-billion (the highest power of 10 that fits in a 32-bit integer) and then convert these "base-1-billion digits" to 9 decimal digits each at the end of your computation.

I have a very dense (rather hard to read) but efficient implementation here, under LGPL MIT license:

http://git.musl-libc.org/cgit/musl/blob/src/stdio/vfprintf.c?h=v1.1.6

If you strip out all the hex float support, infinity/nan support, %g/%f/%e variation support, rounding (which will never be needed if you only want exact answers), and other things you might not need, the remaining code is rather simple.

Proper way to convert a double to string without allocating more memory than required?

You can use NULL as the first argument of snprintf to get the size:

C99 allows str to be NULL and gives the return value (as always) as
the number of characters that would have been written in case the
output string has been large enough.

And then malloc:

int main(void)
{
double num = 3.14;
size_t len;
char *str;

len = (size_t)snprintf(NULL, 0, "%f", num) + 1;
str = malloc(len);
snprintf(str, len, "%f", num);
puts(str);
free(str);
return 0;
}

How do I convert a double into a string in C++?

The boost (tm) way:

std::string str = boost::lexical_cast<std::string>(dbl);

The Standard C++ way:

std::ostringstream strs;
strs << dbl;
std::string str = strs.str();

Note: Don't forget #include <sstream>

Need a fast method to convert large amount of double to string

fast method to convert large amount of double to string

For full double range application, use sprintf(buf, "%a", some_double). If decimal output required, use "%e".

Any other code will only be faster if it is comprises accuracy or allowable input range somehow.

The usual approach is to convert double x to some wide scaled integer and convert that to a string. This implies limitations on x not clearly expressed yet by OP.

Even if some other approaches appears faster, it may not be faster as code evolves or is ported.


What OP needs to post is speed test code for objective performance assessment.



Related Topics



Leave a reply



Submit