cancel
Showing results for 
Search instead for 
Did you mean: 

How to Extract Two Decimal Places Without Rounding in STM32?

ThienNguyen0301
Associate II

 

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!

4 REPLIES 4

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...?

> 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

gbm
Lead III

int a = floor(f * 100f);

My STM32 stuff on github - compact USB device stack and more: https://github.com/gbm-ii/gbmUSBdevice
TDK
Guru

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

 

If you feel a post has answered your question, please click "Accept as Solution".