Page 1 of 1
Integer to float calculation
Posted: Tue Oct 07, 2025 1:30 am
by Billduck1302
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
Re: Integer to float calculation
Posted: Tue Oct 07, 2025 9:19 am
by Steve-Matrix
I think there is an alternative you can use which is this:
Code: Select all
Cell_1_Voltage_Float = (Cell_1_Voltage_Int / 1023.0) * 5.0
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:
Code: Select all
Cell_1_Voltage_Float = (Cell_1_Voltage_Int / 1023) * 5.0
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:
Code: Select all
My_Int_Result = (My_Voltage_Int * 5) / 1023
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).
Re: Integer to float calculation
Posted: Tue Oct 07, 2025 9:49 am
by Steve-Matrix
I forgot another trick, and that is to simplify the calculation (by multiplying by 5/1023) to this instead:
Code: Select all
Cell_1_Voltage_Float = Cell_1_Voltage_Int * 0.0048875855
(if you did this, it would be beneficial to add a comment in the code to explain where that value came from)
Re: Integer to float calculation
Posted: Tue Oct 07, 2025 9:06 pm
by Billduck1302
Thank you sir.