Go4Expert

Go4Expert (http://www.go4expert.com/)
-   PHP (http://www.go4expert.com/forums/php/)
-   -   Function to calculate percentage (http://www.go4expert.com/forums/function-calculate-percentage-t3092/)

pradeep 21Feb2007 12:51

Function to calculate percentage
 
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 21Feb2007 12:56

Re: Function to calculate percentage
 
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 21Feb2007 13:02

Re: Function to calculate percentage
 
Will return 48!

shabbir 21Feb2007 13:20

Re: Function to calculate percentage
 
But it should not as 48/100 in integer should be 0

pradeep 21Feb2007 13:37

Re: Function to calculate percentage
 
the arguments passed are integers, but $res is casted to int.

shabbir 21Feb2007 14:58

Re: Function to calculate percentage
 
What is the type for $per

pradeep 21Feb2007 15:07

Re: Function to calculate percentage
 
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 12Mar2007 05:13

Re: Function to calculate percentage
 
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.


All times are GMT +5.5. The time now is 14:08.