Function to calculate percentage

pradeep's Avatar, Join Date: Apr 2005
Team Leader
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;
 } 
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
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
pradeep's Avatar, Join Date: Apr 2005
Team Leader
Will return 48!
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
But it should not as 48/100 in integer should be 0
pradeep's Avatar, Join Date: Apr 2005
Team Leader
the arguments passed are integers, but $res is casted to int.
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
What is the type for $per
pradeep's Avatar, Join Date: Apr 2005
Team Leader
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.
DaWei's Avatar, Join Date: Dec 2006
Team Leader
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.