Skip to content

Instantly share code, notes, and snippets.

@saleph
Last active December 15, 2016 17:46
Show Gist options
  • Save saleph/064b3157257613539f3fc4fcea30a477 to your computer and use it in GitHub Desktop.
Save saleph/064b3157257613539f3fc4fcea30a477 to your computer and use it in GitHub Desktop.
A function printing float to char* buffer without using %f. Excellent for arduino projects purpose. Fully SIGSEGV-prone. Enjoy!
#include <stdio.h>
/// Prints float to buffer without using %f (for microcontrollers purpose)
///
/// Usage:
/// char buffer[20];
/// printFloatToBuffer(buffer, 20, -3.1415, 3);
/// printf("%s", buffer);
///
void printFloatToBuffer(char *buffer, size_t bufferSize, float val, unsigned int precision) {
int significant = (int)val;
if (precision == 0) {
// print significant w/o separator
snprintf(buffer, bufferSize, "%d", significant);
return;
}
float frac;
if(val >= 0)
frac = (val - significant);
else
frac = (significant - val);
for (unsigned int i = 0; i < precision; ++i)
frac *= 10;
char format[10];
// include leading zeros for fraction (case 23.002 => frac == 2)
snprintf(format, 10, "%%d.%%0%dd", precision);
snprintf(buffer, bufferSize, format, significant, (unsigned int)frac);
}
int main() {
char buf[50];
printFloatToBuffer(buf, 6, -21.6, 1);
printf("%s\n", buf);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment