# C18 precentage calculation

Status
Not open for further replies.

#### hhhsssmmm

##### New Member
Hello

I wish to calculate the precentage of an integer number in C18 compiler. I understand that floating point can be used. However I have read elsewhere on the internet that floating point arithmatic should be avoided as much as possible as its very CPU intensive...especially for PICs.

However, due to my limited knowledge I can not understand other than to simply use floating point.

Below are few lines of C18 code which show my understanding so far of how the precentage can be calculated.

Please can someone look at my code and correct it. Also please provide me feed back for any better and more efficient way of calculating the precentage of a number.

Thank you

Haseeb

Code:
     float precentage = 0; //declaring float variable

precentage = (0x5555/0x8888) * 100.0; //calculating the percentage

#### birdman0_o

##### Active Member
Round 1 / 0x8888 * 100 to the nearest Int. Then multiply your input by that!
No decimals

#### Mr RB

##### Well-Known Member
With integers, always do the multiplication first and the division last. The multiplication is a zero error procedure but the division will introduce an error when it rounds down to integer.

so;
percentage = (0x5555 * 100) / 0x8888
will have a lot less error than;
precentage = (0x5555/0x8888) * 100

If the the second number is always the same it is much easier. So if you have a number X in the range 0-255 and you need it as a percentage you can do this;

percent = (X * 100) / 256

Which is good because the division is binary (256) so it will compile very small.

And if you want to minimise the rounding down error, you add half the divisor BEFORE you do the division;

percent = ((X * 100)+128) / 256

That will give you the closest integer rounded result to the actual floating point result, ie has the least error in the result. I've explained it a bit rushed, one of the math guys can probably explain it much better.

Status
Not open for further replies.

Replies
23
Views
14K
Replies
0
Views
829
Replies
1
Views
607
Replies
4
Views
1K
Replies
7
Views
4K