4
votes

I want to convert a float (e.g. f=1.234) to a char-array (e.g. s="1.234"). This is quite easy with snprintf() but for some size and performance-reasons I can't use it (it is an embedded platform where snprintf() is too slow because it uses doubles internally).

So: how can I easily convert a float to a char-array (positive and negative floats, no exponential representation, maximum three digits after the dot)?

Thanks!

PS: to clarify this: the platform comes with a NEON FPU which can do 32 bit float operations in hardware but is slow with 64 bit doubles. The C-library for this platform unfortunately does not have a specific NEON/float variant of snprintf, so I need a replacement. Beside of that the complete snprintf/printf-stuff increases code size too much

2
There's no easily as the only alternative would be to code the conversion yourself. This would either be very inperformant (using arithmetic operations) or very complicated and require you to know the representation of floating point numbers on your platform.user2371524
" how can I easily convert a float to a char-array" Use library someone else wrote. But if you are on low-end embedded and float performance is an issue, you might want to consider using integers instead.user694733
Use fixed point math. For example, the number 1.234 is stored as 1234.user3386109
multiply by 1000, truncate to int, print with leading zeroes for at least field width of 4, put the decimal point 3 digits from the end.Antti Haapala
or print e-3 after the integer number counting thousandths :PAntti Haapala

2 Answers

2
votes

For many microcontrollers a simplified printf function without float/double support is available. For instance many platforms have newlib nano and texas instruments provides ustdlib.c.

With one of those non-float printf functions you could split up the printing to something using only integers like

float a = -1.2339f;
float b = a + ((a > 0) ? 0.0005f : -0.0005f);
int c = b;
int d = (int)(b * 1000) % 1000;
if (d < 0) d = -d;
printf("%d.%03d\n", c, d);

which outputs

-1.234

Do watch out for overflows of the integer on 8 and 16 bit platforms.

-edit- Furthermore, as by the comments, rounding corner cases will provide different answers than printfs implementation.

0
votes

You might check to see if your stdlib provide strfromf, the low-level routine that converts a float into a string that is normally used by printf and friends. If available, this might be lighter-weight than including the entire stdio lib (and indeed, that is the reason it is included in the 60559 C extension standard).