Printing a float in C while avoiding variadic parameter promotion to double

Xo Wang picture Xo Wang · Apr 2, 2011 · Viewed 8.4k times · Source

How can I print (that is, to stdout) a float in C without having it be promoted to a double when passed to printf?

The issue here is that variadic functions in C promote all float parameter to double, which incurs two unnecessary conversions. For example, if you turn on -Wdouble-promotion in GCC and compile

float f = 0.f;
printf("%f", f);

you will get

warning: implicit conversion from 'float' to 'double' when passing argument to function

I have relatively little processing power to play with (a 72MHz ARM Cortex-M3), and I am definitely bottlenecking on ASCII output of floating point data. As the architecture lacks a hardware FPU to begin with, having to convert between single and double precision does not help matters.

Is there a way to print a float more efficiently in straight C?

Answer

Avoiding the promotion will not save you anything, since the internal double (or more likely long double) arithmetic printf will perform is going to consume at least 1000x as much time. Accurately printing floating point values is not easy.

If you don't care about accuracy though, and just need to print approximate values quickly, you can roll your own loop to do the printing. As long as your values aren't too large to fit in an integer type, first convert and print the non-fractional part as an integer, then subtract that off and loop multiplying by 10 and taking off the integer part to print the fractional part one digit at a time (buffer it in a string for better performance).

Or you could just do something like:

printf("%d.%.6d", (int)x, (int)((x-(int)x)*1000000));