-->
Page 1 of 2

Trouble with floats

PostPosted: Sun Apr 12, 2015 2:59 am
by sh4d0w
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.

Re: Trouble with floats

PostPosted: Sun Apr 12, 2015 5:34 am
by petoknm
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 :)

Re: Trouble with floats

PostPosted: Sun Apr 12, 2015 10:54 am
by sh4d0w
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.

Re: Trouble with floats

PostPosted: Wed Mar 09, 2016 1:02 pm
by metalphreak
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 :)