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

Asked

Viewed 2,441 times

1

The problem is that the numbers have to have two decimal places at all times, only in cases where it is type '3.10' you have to format to '3.1'. How do I do it in C?

  • Floating point numbers are approximate power sum results of 2 (positive and negative), so it is difficult to know when something should only be represented in a single digit after the comma in the decimal system

2 answers

2


The conversion specifier %g is able to display only the significant digits of a type float.

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;
}

Exit:

a = 1.123
b = 3.1415
c = 10

References:

The output conversion specifier %g

Values are displayed in the format %f or %e, depending on what more compact for the value and for the accuracy that have been specified. The format %e will only be used when the value exponent is less than that -4 or greater than or equal to the precision argument. Zeros on the left are truncated, and the decimal point is displayed only if one or more digits come in sequence.

Source: http://man7.org/linux/man-pages/man3/printf.3.html

  • Do you have a reading source? For me to go deeper?

0

The other way to do this by putting %f.1 so every time it will display a house after the comma but will continue working with full number.

  • 1

    Did you mean %f.1? And could [Dit] the answer better explaining your suggestion, with an example etc?

  • The example is still missing :)

  • 1

    Would not be %.1f? I tested with %f.1 and always appears .1 after the value. But still, using only %.1f, only one decimal place will appear, regardless of the value. For example, if I try to display 3.1415, the result would be 3.1, but that’s not the request.

  • You’re right @Anderson, I made a double mistake

Browser other questions tagged

You are not signed in. Login or sign up in order to post.