How do I round a float number from two decimal places to one if I have only one number? example: 2.10 to 2.1

1

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?

    
asked by anonymous 27.06.2017 / 18:09

2 answers

2

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

    
27.06.2017 / 20:23
0

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.

    
28.06.2017 / 01:01