sprintf or printf do not output float variables correctly

Have you run into situation under the MPLAB IDE where you are trying to output variables, but even though you have the format correct, a float variable outputs with a .0 value?

Example

(from somewhere else in code)
AIRTEMP=751
====
float adjustedtemp= 0.0;
adjustedtemp= (AIRTEMP + 5)/10;
printf("Air Temp: %5.2f \r\n", adjustedtemp);

the result looks like this

Air Temp: 75.00

when it SHOULD look like this

Air Temp: 75.60

this is due to a bug in the way MPLAB handles floats.

Two easy ways to fix it:

#1:

adjustedtemp= (AIRTEMP + 5.0)/10.0;

or,

#2

adjustedtemp= ((float)AIRTEMP + 5)/10;

Either of these methods will result in the correct value being displayed during your sprintf() or printf() command.

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.