5

how am I supposed to print a float so as if it has no numbers behind decimal point e.g. 11.00 should be printed as 11 but 11.45 should stay the same. The problem is some if statement maybe. Any suggestions?

MartinT
  • 590
  • 5
  • 21

2 Answers2

2

First solution that comes on my mind is cast. This is what I would do. Let's say your variable is "a", that you want to print.

    float a;

    if (if (a-(int)a<0.001 || (int)a-a<0.001) ) //1st comment explains this 
       printf("%d", (int)a);
    else
       printf("%f", a);
S.Mitric
  • 21
  • 4
0

Here is my solution:

#include <stdio.h>

void printDouble(double fp);

int main(void)
{
    printDouble(11.0);
    printDouble(11.45);
}

void printDouble(double fp)
{
    double _fp;
    char buffer[40];
    int i = 0;
    do{
        sprintf(buffer, "%.*lf", i, fp);
        sscanf(buffer, "%lf", &_fp);
        i++;
    } while(fp != _fp);
    puts(buffer);
}

Output:

11
11.45

Perhaps this is somewhat inefficient, but it does work. Anyway, you don't need to print floating-point numbers frequently.

nalzok
  • 14,965
  • 21
  • 72
  • 139
  • %e doesn't show an integer representation of a float, it uses scientific notation. Therefore, with fp=100000.0, %g will show 1.0e+5, not 100000, which is what the OP is requesting. – Dave Knight Mar 24 '16 at 09:07
  • The presence in the question of `if` statements is significative that the problem should be solved by hand, rather than through a function. – edmz Mar 24 '16 at 09:11
  • @DaveKnight Answer modified – nalzok Mar 24 '16 at 09:55