Percentage calculation driving me crazy !

Hi guys,

This should be the simplest calculation ever but its driving me crazy !

I have a counter (CANBusSearchAddress) which increments from 0 to 3000 whilst searching for a device on my canbus. The counter is definitely incrementing and in fact the routine does find the device. All I want to do now is send the search progress percentage to my LCD screen, but its always zero.

float SearchPercent = (((CANBusSearchAddress) / 3000) * 100);
SearchPercentString = String(int(SearchPercent)) + "%";
lcd.setCursor(15,2);           
lcd.print(SearchPercentString);

Can anyone see why SearchPercentString only ever displays 0% ?

Thanks in advance !

Gareth

Because the calculation is done as integers ?

Try this

float SearchPercent = (((CANBusSearchAddress) / 3000.0) * 100.0);

You're using Integer division.

Try

float SearchPercent = (((CANBusSearchAddress) / 3000.0) * 100);

if CANBusSearchAddress is an integer and its value is less than 3000 the evaluation of the integer division

CANBusSearchAddress) / 3000

will give 0
try

CANBusSearchAddress) / 3000.0f

will calculate using floating point division which will give a fractional component

OMG. Why couldn't I see that ... I've been staring at this for hours !!!

Thank you guys, I feel like a total numpty now !

If you want to do it the integer way you must

  • first multiply by 100
  • add half the divider for rounding (optional)
  • do the division
  • check for possible overflow (CANBusSearchAddress should be a 32 bit int.

float SearchPercent = (CANBusSearchAddress * 100 + 1500) / 3000;

Next time you sit in front of a coding-problem.
Start adding serial printing which prints each and every step of a calculation step by step
another ten minutes and you will have found the bug.

The secret is to STOP all assumings
and print really every single step
print CANBusSearchAddress
print CANBusSearchAddress / 3000
print (CANBusSearchAddress / 3000) * 100

1 Like

Good work spelling numpty correctly !

@angelina_robert_421
Please do not post the robot's answers to the forum, write your own suggestions.
The forum does not welcome copy-paste from chatgpt.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.