Guys, I want to know if float
variables can be used in sprintf()
function.
Like, if we write:
sprintf(str,"adc_read = %d \n",adc_read);
where adc_read
is an integer variable, it will store the string
"adc_read = 1023 \n"
in str
(assuming that adc_read = 1023
)
How can I use a float variable in place of integer?
Don't expect sprintf (or any other function with varargs) to automatically cast anything. The compiler doesn't try to read the format string and do the cast for you; at runtime, sprintf has no meta-information available to determine what is on the stack; it just pops bytes and interprets them as given by the format string. sprintf(myvar, "%0", 0); immediately segfaults.
So: The format strings and the other arguments must match!
Yes, use %f
Don't do this; integers in C/C++ are always rounded down so there is no need to use the floor function.
Better to use
Then you won't get rounding up of the integer part (68.9999999999999999 becomes 69.00..). 68.09999847 instead of 68.1 is difficult to avoid - any floating point format has limited precision.
use the
%f
modifier:For instance:
Yields this:
Yes you can. However, it depends on the C-library that you are linking against and you need to be aware of the consequences.
Since you are programming for embedded applications, realise that floating-point support is emulated for a lot of embedded architectures. Compiling in this floating-point support will end up increasing the size of your executable significantly.
Similar to paxdiablo above. This code, inserted in a wider app, works fine with STM32 NUCLEO-F446RE.
counter_buff would contain 123.056 .