You want a quick and dirty way to produce a string with the decimal representation of your float without linking sprintf
because of space constraints on an embedded system. The number of decimals is fixed. Here is a proposal:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *ftoa(char *dest, size_t size, double val, int dec) {
char *p = dest;
char *q = dest + size;
long long mul = 1;
long long num;
int i;
if (size == 0)
return NULL;
*--q = '\0';
if (size == 1)
goto fail;
if (val < 0) {
val = -val;
if (p >= q)
goto fail;
*p++ = '-';
}
for (i = 0; i < dec; i++) {
mul *= 10;
}
num = (long long)(val * mul + 0.5);
for (i = 1; i < dec + 2 || num > 0; i++) {
if (p >= q)
goto fail;
*--q = '0' + (num % 10);
num = num / 10;
if (i == dec) {
if (p >= q)
goto fail;
*--q = '.';
}
}
memmove(p, q, dest + size - q);
return dest;
fail:
return memset(dest, '*', size - 1);
}
int main(int argc, char *argv[]) {
char buf[24];
for (int i = 1; i < argc; i++) {
double d = strtod(argv[i], NULL);
int dec = 5;
if (i + 1 < argc)
dec = atoi(argv[++i]);
printf("%s\n", ftoa(buf, sizeof buf, d, dec));
}
return 0;
}