Float to int if num has no numbers behind the decimal point in C

how should I print a float as if it had no number behind the decimal point, for example. 11.00 should be printed as 11, but 11.45 should remain unchanged. The problem may be in some cases. Any suggestions?

+5
source share
2 answers

The first decision that comes to my mind is a throw. This is what I would do. Say your variable "a" you want to print.

float a; if (if (a-(int)a<0.001 || (int)aa<0.001) ) //1st comment explains this printf("%d", (int)a); else printf("%f", a); 
+2
source

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 

This may be somewhat inefficient, but it works . Anyway, you don't need to print floating point numbers often.

0
source

Source: https://habr.com/ru/post/1245684/


All Articles