This is much needed, as for IoT we will be dealing with lots of floats, like temp, rainfall, voltage, etc.
I had to implement quick float function, but it's probably not covering lots of edge cases...
Code: Select all
int power(int base, int exp){
int result = 1;
while(exp) { result *= base; exp--; }
return result;
}
static char* ftoa(float num, uint8_t decimals) {
// float to string; no float support in esp8266 sdk printf
// warning: limited to 15 chars & non-reentrant
// e.g., dont use more than once per os_printf call
static char* buf[16];
int whole = num;
int decimal = (num - whole) * power(10, decimals);
if (decimal < 0) {
// get rid of sign on decimal portion
decimal -= 2 * decimal;
}
char* pattern[10]; // setup printf pattern for decimal portion
os_sprintf(pattern, "%%d.%%0%dd", decimals);
os_sprintf(buf, pattern, whole, decimal);
return (char *)buf;
}