Is it possible to format a float in C to only show up to 2 decimal places if different from 0s using printf?
Ex:
12 => 12
12.1 => 12.1
12.12 => 12.12
I tried using:
float f = 12;
printf("%.2f", f)
but I get
12 => 12.00
12.1 => 12.10
12.12 => 12.12
You can use the
%gformat specifier:Result:
Note that, unlike the
fformat specifier, if you specify a number before thegit refers to the length of the entire number (not the number of decimal places as withf).