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
A double cannot be converted to a char*. If you're simply trying to get a string representation of the double, you're going to have to convert it to a char array. A function accepting a char* will accept a char[].
The c_str() and strcpy() function in C++ C++ c_str() function along with C++ String strcpy() function can be used to convert a string to char array easily. The c_str() method represents the sequence of characters in an array of string followed by a null character ('\0'). It returns a null pointer to the string.
You are translating the literal bytes of your double
into char
s. 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)
You are copying a double
(which is a binary representation for a number) into a char
array; there is no reason those bytes should correspond to digit characters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With