printf in different forms

Viewed 85

I have a data type of double, I want to printf the double in the following form:

  • If double x=2 or x=2.0 print 2 to the screen, which means if I get an integer I print an integer.
  • If double x=2.3 or x=2.30 or any other non-whole number I print 2.3 to the screen.

Is there any way to do it shortly? or do I need to use if statements or something like that?

double x = 2;
printf("%d", x);
double x = 2.3;
printf("%.1f", x);

This is an illustration only. I want to printf an integer or a double based on the value I get.

3 Answers

The quick and dirty way to print a double with a minimal number of decimals without an extra loop is to use the %g conversion specifier.

#include <stdio.h>

void print_num(double x) {
     printf("%g", x);
}

Very small and very large values may require a more explicit approach to avoid the exponent form:

#include <stdio.h>

void print_num(double x) {
    char buf[500];
    int n = snprintf(buf, sizeof buf, "%.15f", x);
    while (n > 0 && buf[n - 1] == '0') {
        buf[--n] = '\0';
    }
    if (n > 0 && buf[n - 1] == '.') {
        buf[--n] = '\0';
    }
    printf("%s", buf);
}

If OP wants one decimal place after the . when the value of not a whole number:

Use ".*" and trunc() to control number of precision digits.

trunc() returns the double with the fractional part truncated.

double f = 2.3;
printf("%.*f\n", f != trunc(f), f);  // 1 digit
f = 2.0;
printf("%.*f\n", f != trunc(f), f);   // 0 digits, no .

Output

2.3
2

Consider i is an int variable. Assign value of x into the i before check like i==x. It will be assigned truncate value of x. then

if(i==x) printf("%d",i);

i==x will be only true when x won't have any fragment.

else printf("%.1f",x);
Related