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
to_string
? – Macedoniandouble
is not an array ofchar
. If it was that simple there would be no need forstd::to_string
. There's a lot of work involved in converting a floating-point value to a text string. For a somewhat simpler problem, try converting anint
value into a string. Once you've got that working you can start to think about floating-point conversions. Or you can just use the built-in library facilities. The last time I wrote a floating-point to text conversion function it took several weeks. This is not a beginner's task. – Angelestd::to_string
is so abhorrent, perhaps C APIs likesprintf
would do what you need? – Takashi