Skip to main content
Graduate
September 30, 2024
Question

How to Extract Two Decimal Places Without Rounding in STM32?

  • September 30, 2024
  • 4 replies
  • 1654 views

 

Dear STM32 Community,

I am currently working on a project using STM32CubeIDE, and I need to perform calculations that involve floating-point numbers. Specifically, I would like to extract exactly two decimal places from a float number without rounding. For example, if the value is 1.61859652354, I want to obtain 1.61 (not 1.62).

I have tried rounding methods, but they do not meet my requirements as they round the value up or down. Instead, I need a way to truncate the value after two decimal places for further use in my calculations.

Could anyone suggest the best approach or method to achieve this in STM32CubeIDE?

Thank you in advance for your help!

    This topic has been closed for replies.

    4 replies

    Super User
    September 30, 2024

    It may not be possible, because not all decimal values can be exactly represented in binary.

     

    https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

     

    Perhaps explain what it is you're trying to achieve here - there may be a better way; use suitably-scaled integers...?

    Super User
    September 30, 2024

    > It may not be possible, because not all decimal values can be exactly represented in binary.

    One way to tackle this is to use an integer representation, in hundredth (i.e. scaled by 100).

    JW

    Graduate
    September 30, 2024

    int a = floor(f * 100f);

    Super User
    September 30, 2024

    Multiply by 100, round down, then divide by 100. That will get you the closest to what you want.

    float round_to_hundredths(float x) {
     return floor(x * 100.0f) / 100.0f;
    }