Float rounding in C

5

I need to return a value float with 1 decimal place, however it is returning with the value rounded.

I have the following code:

float n1 = 4;
float n2 = 9;

float total = n2 / n1 ;

printf("Media: %.1f ", total ); //aqui, o resultado é 2.3

printf("Media: %.2f", total); //aqui, o resultado é 2.25

The expected value should be Média = 2.2 , but it is returning 2.3 .

Is there a solution?

    
asked by anonymous 23.05.2014 / 20:21

1 answer

6
float n1 = 4;
float n2 = 9;

float total = n2 / n1 ;
float truncado = floor( total * 10.0f ) / 10.0f;

printf("Media: %.1f ", truncado );
printf("Media: %.2f ", truncado );
printf("Media: %.5f ", truncado );
  

Change the two 10.0f as you want. For example, 1000.0f to 3 houses.

Technically what you mentioned is a truncation (or rounding down) instead of traditional rounding (4/5), which is the behavior of %.1f .

If you want a more specific answer, say the desired criterion (eg round to pair, truncate to larger, use rounding 4/5, use rounding 5/6, etc.)

Click here and see the code working at IDEONE .

    
23.05.2014 / 20:46