Search code examples
cfloating-pointembeddedstm32

Round float in C in STM32F


I'd like to round two float values two only two decimals.

This is the array of floats:

float result[2];

This is the rounding operation:

result[0] = roundf( result[0] * 100 ) / 100;
result[1] = roundf( result[1] * 100 ) / 100;

For the value of :

-3.99520659

I expect -4, and I get -4

But For the value of :

8.07999992

I expect 8, but I get the same number.

For other ocasions I'd like the numbers to look like 3.4 o -2.1

What can I do?

Thanks!


Solution

  • Your code is probably correctly rounding 8.07999992 to 8.08. But then it's probably getting printed out as 8.07999992 again. This is due to the limited precision of floating point (and the even more limited precision of type float as opposed to double), and the fact that, in binary, there is no such number as 8.08.

    Try these two things:

    1. Print your result using %.2f, and again using %.20f. (I assume you're using printf.)
    2. Use type double instead of float.

    The other question to ask is, why are you trying to round these numbers? Is it because they're only significant to two places? Is it because you want to display them that way? Is it because they're supposed to represent dollars and cents (or some other centidecimal currency)?

    • If the quantities are only significant to two places, rounding as you're currently doing should be correct.
    • If you want to display a floating-point number to two places, just use %.2f, and don't worry about explicitly rounding it yourself.
    • If you're trying to manipulate dollars and cents, it's often much easier to use integer math (representing cents) across the board.