2024-09-30 08:07 AM
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!
2024-09-30 08:10 AM - edited 2024-09-30 08:18 AM
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...?
2024-09-30 08:20 AM
> 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
2024-09-30 08:25 AM
int a = floor(f * 100f);
2024-09-30 08:28 AM
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;
}