I learned something today. Namely, I had to insert "FLOAT" in the following expression.
Cell_1_Voltage_Float = (FLOAT (Cell_1_Voltage_Int) / 1023) * 5.0
Integer to float calculation
-
- Posts: 23
- http://meble-kuchenne.info.pl
- Joined: Fri Dec 06, 2024 4:41 pm
- Has thanked: 1 time
- Been thanked: 1 time
-
- Matrix Staff
- Posts: 1595
- Joined: Sat Dec 05, 2020 10:32 am
- Has thanked: 222 times
- Been thanked: 373 times
Re: Integer to float calculation
I think there is an alternative you can use which is this:
For those who are interested, here's what's going on:
Without the (FLOAT) casting or the addition of the ".0", the C compiler will see this:
It evaluates the part in brackets first and sees that both values are integers and incorrectly assumes you want an integer as a result. Usually this will be something like "456/1023" which will equate to zero rather than 0.4457... and multiplying that by 5.0 will also produce zero.
The trick of the "FLOAT" or the ".0" is to tell the compiler that one of the operands is actually a float and therefore the result should also be a float.
If you wanted to avoid floats totally, there is another trick you can use, and that is to perform the calculation like this instead:
It will not be perfect (as integer divisions will be truncated rather than rounded), but if My_Voltage_Int is 456, then the calculation becomes 2280/1023 and equates to 2 (rather than zero if the division is performed first because of the brackets in the earlier form).
Code: Select all
Cell_1_Voltage_Float = (Cell_1_Voltage_Int / 1023.0) * 5.0
Without the (FLOAT) casting or the addition of the ".0", the C compiler will see this:
Code: Select all
Cell_1_Voltage_Float = (Cell_1_Voltage_Int / 1023) * 5.0
The trick of the "FLOAT" or the ".0" is to tell the compiler that one of the operands is actually a float and therefore the result should also be a float.
If you wanted to avoid floats totally, there is another trick you can use, and that is to perform the calculation like this instead:
Code: Select all
My_Int_Result = (My_Voltage_Int * 5) / 1023
-
- Matrix Staff
- Posts: 1595
- Joined: Sat Dec 05, 2020 10:32 am
- Has thanked: 222 times
- Been thanked: 373 times
Re: Integer to float calculation
I forgot another trick, and that is to simplify the calculation (by multiplying by 5/1023) to this instead:
(if you did this, it would be beneficial to add a comment in the code to explain where that value came from)
Code: Select all
Cell_1_Voltage_Float = Cell_1_Voltage_Int * 0.0048875855
-
- Posts: 23
- Joined: Fri Dec 06, 2024 4:41 pm
- Has thanked: 1 time
- Been thanked: 1 time