Float rounded in C

Asked

Viewed 11,317 times

6

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

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 is returning 2.3.

Is there any solution?

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 wish. For example, 1000.0f for 3 houses.

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

If you want a more specific answer, say the desired criterion (e.g., round to even, truncate to larger, round to 4/5, round to 5/6, etc).

Click here and see the code in operation on IDEONE.

  • Bacco, the problem is in the round coming value. I don’t want it round

  • @Tercio remember that you can use the truncado just in time to display on screen, if you prefer, and continue using the total for other things. If you need any further detail, explain here that I can try to increment the answer.

  • @Bacco What do you think of printf("Media: %.2f\b ", total);? The \b solves, but I don’t know if it’s a safe solution.

  • 1

    @Lucasnunes I wouldn’t risk, it depends a lot on the output device (imagine a redirect to file, for example). And suddenly he might want to use the value in a graphical interface later, then the solution wouldn’t work. I like the idea of using the variable for another reason too, if it needs to make sums, the total will match what was shown on the screen (but, of course, are only hypotheses).

Browser other questions tagged

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