# Function to calculate percentage

Discussion in 'PHP' started by pradeep, Feb 21, 2007.

Joined:
Apr 4, 2005
Messages:
1,645
87
Trophy Points:
0
Occupation:
Programmer
Location:
Kolkata, India
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:
``` function percentage(\$int1, \$int2)  {     \$per = \$int1 / \$int2;     \$res = \$per * 100;     return \$res; } ```

2. ### shabbirAdministratorStaff Member

Joined:
Jul 12, 2004
Messages:
15,374
388
Trophy Points:
83
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

Joined:
Apr 4, 2005
Messages:
1,645
87
Trophy Points:
0
Occupation:
Programmer
Location:
Kolkata, India
Will return 48!

4. ### shabbirAdministratorStaff Member

Joined:
Jul 12, 2004
Messages:
15,374
388
Trophy Points:
83
But it should not as 48/100 in integer should be 0

Joined:
Apr 4, 2005
Messages:
1,645
87
Trophy Points:
0
Occupation:
Programmer
Location:
Kolkata, India
the arguments passed are integers, but \$res is casted to int.

6. ### shabbirAdministratorStaff Member

Joined:
Jul 12, 2004
Messages:
15,374
388
Trophy Points:
83
What is the type for \$per

Joined:
Apr 4, 2005
Messages:
1,645
87
Trophy Points:
0
Occupation:
Programmer
Location:
Kolkata, India
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.

8. ### DaWeiNew Member

Joined:
Dec 6, 2006
Messages:
835
5
Trophy Points:
0
Occupation:
Semi-retired EE
Location:
Texan now in Central NY