Chat freely about anything...

User avatar
By sh4d0w
#14252 So I am trying to carry out some caclulations with floats and I am comming up with the following issues:

[1] I can not seem to get it to print floats to the terminal, all it keeps doing is printing %f. I have tried placing the variable directly in the command:
Code: Select allos_printf("%f", float_value);


as well as writing it to a buffer then trying to output the buffer
Code: Select allets_sprintf(_Temp,"%f", float_time);


All I end up with is a load of %f in the output.
What am I doing wrong?

[2] The second is what float methods are available? I have tried a few that exist in the math.h file and some seem ok and for others it throws up errors. I am mainly looking to find the remainder of a division. Furthermore I can't seem to get the modulo (%) operator to work.


Any and all guidance and help would be greately appreciated.
User avatar
By petoknm
#14265 I had the same problem... I solved it by making my own function that appends the float to a string... It prints exactly 2 decimal places...
Code: Select allvoid ICACHE_FLASH_ATTR printFloat(float val, char *buff) {
   char smallBuff[16];
   int val1 = (int) val;
   unsigned int val2;
   if (val < 0) {
      val2 = (int) (-100.0 * val) % 100;
   } else {
      val2 = (int) (100.0 * val) % 100;
   }
   if (val2 < 10) {
      os_sprintf(smallBuff, "%i.0%u", val1, val2);
   } else {
      os_sprintf(smallBuff, "%i.%u", val1, val2);
   }

   strcat(buff, smallBuff);
}

Hope it helps :)
User avatar
By sh4d0w
#14293 Thanks, that is awesome!
Well the function is awesome, but the fact that we need to write our own function is less awesome.

Thanks again.
User avatar
By metalphreak
#42765 Works well, thanks for the example. I noticed some issues modifying it for precision with 4 or more decimal places, but up to 3 seems to work ok.

BTW, you can replace this section:

Code: Select all   if (val2 < 10) {
      os_sprintf(smallBuff, "%i.0%u", val1, val2);
   } else {
      os_sprintf(smallBuff, "%i.%u", val1, val2);
   }


with simply this
Code: Select allos_sprintf(smallBuff, "%i.%02u", val1, val2);


0 is the flag which means "pad with zeros not spaces"
2 is the width - single digit values will be padded with spaces (changed to 0's with the above flag)
u is unsigned int (as you know)

Saves you a tiny bit of code space :)