Precision loss in calculation

I'm trying to get a percentage of something but I have read the Arduino doesn't handle floats very efficiently especially when it comes to displaying them on a LCD screen.

My statement is as follows:

float percentage = (value / (gAVG * 2))*100;

both value and gAVG variables are integers but I'm sure the calculation will throw some decimal places. Every time I execute this line (no matter what the values of both variables are) I always get percentage = 0.

I'm new to C type language and don't get where it's going wrong?

It is doing the division as an integer before it is converted into a float. therefore the result of this division is always less than 1 so is being translated to zero before being multiplied by 100.
Make all variables float or cast them as float in the expression.

Arduino doesn't handle floats very efficiently

No hardware support true but as efficiently as any other 8 bit micro.

Try

percentage = ((float) value / ((float) gAVG * 2.0))*100.0;

This will take more time and code space for the floating point emulation, but it'll work.

You could also try

percentage = (value * 100) / (gAVG * 2);

which is mathematically equivalent to your first expression but reorders the operations in such a way to avoid the problem you see. It will still have integer rounding issues, but it avoids the computational penalty for floating point calculations.

-j

Thank you Grumpy_Mike for your reply and thank you very much for the code examples kg4wsv.

It has worked now with both casting and multiplying the value. :slight_smile: