The problem is that numbers must always have two decimal places, only in cases where '3.10' has to be formatted to '3.1'. How do I do this in C?
The problem is that numbers must always have two decimal places, only in cases where '3.10' has to be formatted to '3.1'. How do I do this in C?
The %g
conversion specifier is able to display only the significant digits of a float
type.
For example:
#include <stdio.h>
int main( int argc, char * argv[] )
{
float a = 1.1230000;
float b = 3.14150000;
float c = 10;
printf( "a = %g\n", a );
printf( "b = %g\n", b );
printf( "c = %g\n", c );
return 0;
}
Output:
a = 1.123
b = 3.1415
c = 10
References:
The output conversion specifier
%g
Values are displayed in
%f
or%e
format, depending on what more compact for the value and accuracy that were specified. The format%e
will only be used when the value exponent is less than which% is equal to or greater than or equal to the precision argument. Left Zeros are truncated, and the decimal point is displayed only if one or more digits follow.
Source: link
The other way of doing this, putting% f.1 so every time it will display a house after the comma, but will continue working with full number.