2020-06-07 07:06 AM
I have win forms GUI and sending data from this GUI to STM32 Nucleo L4R5ZI µC over UART in byte array format. After receiving data over UART in µC, I am converting the data to their native formats such as Int ad Float. I don't have issue converting int, but float data is converted with too much precision i.e) 1.3 from GUI is converted as 1.29999995 in cubeIDE. That'y I implemented a function with sprintf and sscanf to convert 1.29999995 to 1.3. Sprintf copied the value to str (str is char array) 1.30, but sscanf is unable to copy the value back to float variable. Please have a look at the image for more info and also have a look at the code snippet. Please help me in this regard.
float conv(float var)
{
convvar = var;
sprintf(str, "%.2f", convvar);
// scan string value in var
sscanf(str, "%f", &convvar);
return convvar;
}
2020-06-07 07:20 AM
float has limited precision. The value 1.3 can't be exactly represented, so it's choosing the closest one. No bug here.
Do "float x = 1.3f;" and you'll find it gets the same 1.29999995 value.
2020-06-07 07:26 AM
Hi TDK. Thanks for the reply. I understand your answer. But, my problem is why sscanf is unable to copy the value in str to convvar ? If that is possible then I can retrieve the original value i.e) 1.3.
2020-06-07 07:32 AM
Your screenshot shows a value of 1.29999995 in convvar. Why do you think it's not there?
2020-06-07 07:39 AM
Please look at the live expression window. I am passing 1.29999995 in convvar. After sprintf statement, the value in convvar which is 1.29999995 is limited to 2 deciaml places and copies 1.30 to str (you can check from live expression window in the screenshot). My question is why sscanf is unable to copy the value 1.30 from str to convvar ?
2020-06-07 07:52 AM
> My question is why sscanf is unable to copy the value 1.30 from str to convvar ?
Because the exact value of 1.3 is not representable as a variable of type float, as I wrote in the first response.
2020-06-07 08:04 AM
Could you please have a look at the 3rd method mentioned in the below link
https://www.geeksforgeeks.org/rounding-floating-point-number-two-decimal-places-c-c/
Why is it not possible to achieve the same functionality in STM32CubeIDE?
2020-06-07 08:23 AM
You're not doing the same thing. They're using cout to print and examine the variable whereas you're examining the exact value in the register. Go compile their code on your computer and you'll find that var is not exactly 37.67 despite what is output in cout.
I suggest reading https://en.wikipedia.org/wiki/Single-precision_floating-point_format
2022-07-15 04:28 AM
May be I am very late to answer this. :;
In order to use 'float' type with 'scanf' and 'printf' functions in CubeIde, you need to enable it in project settings.
Hopefully this solves your issue. And this will parse float 'string' to a float variable.
2024-05-08 07:40 AM
thank you #PMish.1 for the solution:)