-1
double d = 3.3;
char str[50];
sprintf(str, " \t%f", d);
USBD_VCOM_SendString(str);

Wanted to send the double from my µController to my Computer but str always seams to be empty. Tried it with int too and it worked fine. Also doesn´t work for float. I´m using a ARM-GCC C Compiler.

Shilence
  • 29
  • 3
  • Looks as if floating point number formatting is not implemented in your CRT. – Jabberwocky Jul 28 '16 at 12:35
  • Thanks. That sounds like a big problem. Any other ways to convert a float or double to a char array? – Shilence Jul 28 '16 at 12:38
  • I'm not completely sure, it just _looks_ so. Have a look into the documentation and/or the source code of the CRT whch should be available. – Jabberwocky Jul 28 '16 at 12:39
  • Check the return value from `sprintf()`; it should report the number of characters written to the string. It's usually a good idea to use `snprintf()` to ensure no buffer overflow — a value such as 1E+123 will overflow your buffer handily, which is bad news (even if the value is unlikely to occur, which I fully accept). – Jonathan Leffler Jul 28 '16 at 12:57
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example. – too honest for this site Jul 28 '16 at 13:21
  • Using `ptintf` & friends on a MCU is most certainly a bad idea. Similar for using floating point - worse `double`. It often is a signal of bad system design. Use integers as fractional/fixed point or at least `float`. – too honest for this site Jul 28 '16 at 13:22
  • Send the value with binary format and use the `printf` family function on PC side. – LPs Jul 28 '16 at 13:36

1 Answers1

0

3 issues that need to be resolved.

1) Some compilers, even with *printf() using floating point specifiers, do not include FP support unless code has FP math elsewhere in the code. Insure code uses FP elsewhere or that the compiler does not have this limitation.

2) Use a buffer and *printf() specifier that will not overflow. @Jonathan Leffler
"%e" rather than "%f"is an easy approach to avoid excessively long strings.

3) Print with sufficient precision.

#include <float.h>
//       -   d   .       ddddddd             e   -  expo \0  spare
char str[1 + 1 + 1 + (DBL_DECIMAL_DIG - 1) + 1 + 1 + 5 + 1 + 10];
snprintf(str, sizeof str, "%.*e",  DBL_DECIMAL_DIG - 1, d);

USBD_VCOM_SendString(str);
Community
  • 1
  • 1
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256