Function to calculate percentage

Team Leader
21Feb2007,12:51   #1
pradeep's Avatar
I had to write the code to get percentage every time I needed it, so I thought it'd be much better to have a function for the purpose, here's the function I wrote.

PHP Code:
function percentage($int1$int2
 {
     
$per $int1 $int2;
     
$res $per 100;
     return 
$res;
 } 
Go4Expert Founder
21Feb2007,12:56   #2
shabbir's Avatar
This is not a good way of doing it as you may not get correct results. I am not sure about it in PHP but let me know what is the output for the forllowing.
$int1 = 48
$int2 = 100
Team Leader
21Feb2007,13:02   #3
pradeep's Avatar
Will return 48!
Go4Expert Founder
21Feb2007,13:20   #4
shabbir's Avatar
But it should not as 48/100 in integer should be 0
Team Leader
21Feb2007,13:37   #5
pradeep's Avatar
the arguments passed are integers, but $res is casted to int.
Go4Expert Founder
21Feb2007,14:58   #6
shabbir's Avatar
What is the type for $per
Team Leader
21Feb2007,15:07   #7
pradeep's Avatar
By default there is not data type specified to a variable, it takes the data type of the value assigned. e.g. $a = 10/6; here $a becomes float, and $a = 10/2 here $a becomes int and $a = 'Shabbir' here $a becomes string.
So in this case $per = $int1 / $int2; $per becomes float.
Team Leader
12Mar2007,05:13   #8
DaWei's Avatar
I would suggest that the parameters shouldn't be ints, anyway. Someone might want to know the percentage of a fractional number. Someone also might think that the return type has been coerced to match an the input arguments (integers), rather than having been set by PHPs "autotyping".

I would also suggest that the relationship, a/b*100, is far too simple to waste the overhead of a function call. On the other hand, I come from the days when resources weren't so abundant that one could be profligate with them.