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?
Asked
Active
Viewed 128 times
5
-
4What did you try? And how many decimal places do you want printed. Suppose you have `1.124` or one seventh `0.14285714285714285714285714285714`? – Weather Vane Mar 24 '16 at 08:56
-
4`printf("%g\n", var);` where `var` is the name of your variable. – Spikatrix Mar 24 '16 at 08:58
-
Take a look [here](http://stackoverflow.com/a/5913115/3436922) – LPs Mar 24 '16 at 09:00
-
1BTW, if this is about currency, then you shouldn't store money in floats. – Antti Haapala -- Слава Україні Mar 24 '16 at 09:02
-
1Possible duplicate of [Avoid trailing zeroes in printf()](http://stackoverflow.com/questions/277772/avoid-trailing-zeroes-in-printf) – nwellnhof Mar 24 '16 at 14:22
-
I think I have solved it by simply rounding the value and if rounded one is equal to original value, I will simply use %.0f formatting, else %.2f – MartinT Mar 24 '16 at 20:21
2 Answers
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
-
If a is 123.000001 this won't work. Always compare to some minimum, so: `if (a-(int)a<0.001 || (int)a-a<0.001) ...` – Paul Ogilvie Mar 24 '16 at 09:19
-
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
-