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?
Isn't something like this really easier:
Many embedded systems have a limited snprintf function that doesn't handle floats. I wrote this, and it does the trick fairly efficiently. I chose to use 64-bit unsigned integers to be able to handle large floats, so feel free to reduce them down to 16-bit or whatever needs you may have with limited resources.
Yes of course, there is nothing special with floats. You can use the format strings as you use in printf() for floats and anyother datatypes.
EDIT I tried this sample code:
Output was : Test=0.61
%g can do this:
Look in the documentation for sprintf for your platform. Its usually %f or %e. The only place you will find a definite answer is the documentation... if its undocumented all you can do then is contact the supplier.
What platform is it? Someone might already know where the docs are... :)
Since you're on an embedded platform, it's quite possible that you don't have the full range of capabilities from the
printf()
-style functions.Assuming you have floats at all (still not necessarily a given for embedded stuff), you can emulate it with something like:
You'll need to restrict how many characters come after the decimal based on the sizes of your integers. For example, with a 16-bit signed integer, you're limited to four digits (9,999 is the largest power-of-ten-minus-one that can be represented).
However, there are ways to handle this by further processing the fractional part, shifting it by four decimal digits each time (and using/subtracting the integer part) until you have the precision you desire.
Update:
One final point you mentioned that you were using
avr-gcc
in a response to one of the other answers. I found the following web page that seems to describe what you need to do to use%f
in yourprintf()
statements here.As I originally suspected, you need to do some extra legwork to get floating point support. This is because embedded stuff rarely needs floating point (at least none of the stuff I've ever done). It involves setting extra parameters in your makefile and linking with extra libraries.
However, that's likely to increase your code size quite a bit due to the need to handle general output formats. If you can restrict your float outputs to 4 decimal places or less, I'd suggest turning my code into a function and just using that - it's likely to take up far less room.
In case that link ever disappears, what you have to do is ensure that your gcc command has
"-Wl,-u,vfprintf -lprintf_flt -lm
". This translates to:printf()
library for searching.