Elmi
Elmi

Reputation: 6203

looking for snprintf()-replacement

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

Upvotes: 4

Views: 840

Answers (2)

Chris Dodd
Chris Dodd

Reputation: 126378

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).

Upvotes: 0

Lanting
Lanting

Reputation: 3068

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.

Upvotes: 2

Related Questions