Search code examples
c++stringdoublec-strings

Convert double to Char Array C++


I'm trying to convert (and round) a double to a char array without converting with a std::to_string on the double first. However, I'm receiving random memory text instead. What am I doing wrong?

Here is my code:

double d = 1.0929998; 
d = std::round(d * 100) / 100;

char s[sizeof(d)];
std::memcpy(s,&d,sizeof(d));

Result:

s: q=×£pñ?

Intended value:

s: 1.09


Solution

  • You are translating the literal bytes of your double into chars. The double value is a binary representation (usually something like IEEE 754) while a char is a binary representation of a character (usually something based on ASCII). These two are not compatible.

    Unfortunately, this means that you must do some kind of conversion process. Either the std::to_string() that you said you don't want to do, or a more complicated std::stringbuf (which will call std::to_string() under the hood anyway)