Is there a way to automatically printf a float to the number of decimal places it has?

Viewed 443

I've written a program to display floats to the appropriate number of decimal places:

#include <stdio.h>

int main() {
    printf("%.2f, %.10f, %.5f, %.5f\n", 1.27, 345.1415926535, 1.22013, 0.00008);
}

Is there any kind of conversion character that is like %.(however many decimal places the number has)f or do they always have to be set manually?

2 Answers

Is there a way to automatically printf a float to the number of decimal places it has?

Use "%g". "%g" lops off trailing zero digits.

... unless the # flag is used, any trailing zeros are removed from the fractional portion of the result and the decimal-point character is removed if there is no fractional portion remaining. C17dr § 7.21.6.1 8.

All finite floating point values are exactly representable in decimal - some need many digits to print exactly. Up to DBL_DECIMAL_DIG from <float.h> (typically 17) significant digits is sufficient - rarely a need for more.

Pass in a precision to encourage enough output, but not too much.

Remember values like 0.00008 are not exactly encoded in the typical binary floating point double, but a nearby value is used like 8.00000000000000065442...e-05

printf("%.*g\n", DBL_DECIMAL_DIG, some_double);

printf("%.17g, %.17g, %.17g, %.17g\n", 1.27, 345.1415926535, 1.22013, 0.00008);
// 1.27, 345.14159265350003, 1.2201299999999999, 8.0000000000000007e-05

DBL_DIG (e.g. 15) may better meet OP's goal.

printf("%.15g, %.15g, %.15g, %.15g\n", 1.27, 345.1415926535, 1.22013, 0.00008);
// 1.27, 345.1415926535, 1.22013, 8e-05

Function to print a double - exactly may take 100s of digits.

sprintf() could help you
There is no direct way to do this in my experience
here is a simple algorithm to help you with this function

munber = float/double input
n = number of decimal places in float/double
char format[999];
sprintf(format ,"%%.%df" ,n);
printf(format, number);

sprintf is like printf but instead of writing to stdout, sprintf writes to a string.

Now you are left with finding number of digits after the precision.

Related