|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2000-10-24 08:08 UTC] maxim at maxim dot cx
Hello Developers,
While making a simple class that would calculate few statistics about my visitors I came up with this:
function percent($num1, $num2, $int, $dec=0)
{
$sum = $num1+$num2;
if($sum==0) return 0;
return round(${"num$int"}*100/$sum+0.00000001,$dec);
}
This is a very simple function to calculate percentage of two numbers.
an Example of use:
# In a room there are:
$males = 42;
$females = 67;
# To calculate what percent of the males is currently in the room the call to the function would be:
$male_percent = percent($males, $females, 1);
# Female's percentage?
$female_percent = percent($males, $females, 2);
# We could of course do 100-$male_percent to know $female_percent
# but if this is a class, loop or something then switch $int to 2 would often be much simpler, though.
The option to select the number is very useful for me when the data rotates in different orders and the numbers to base on need to be switched.
An optional $dec is the [int] of round() to pass.
And since I like round to be more precise there is +0.00000001.
I am sure that percent() could be made simpler by adding some more portability to it.
For example it would be useful optionally not to require both numbers passing to percent() only the $sum and a number right away. But once again it is nice (at least for me) to be able to switch between numbers.
Please forgive me if this idea was up there long before me and/or if this function is completely useless.
Just though that it would be nice to have one like this. (PHP doesn't have one yet, right?)
Maxim Maletsky
maxim@maxim.cx
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Oct 29 06:00:01 2025 UTC |
Just to add: this version is much simpler then the one I posted before, however to switch between integrers here is a little harder: function percent($num1, $num2, $dec=0){ $sum = $num1+$num2; if($sum==0) return 0; return round($num1*100/$sum+0.00000001,$dec); } Maxim Maletsky maxim@maxim.cxjust one small correction: the above wouldn't work correctly. There was a useless $sum.. this is my code: function percent($num, $sum, $dec=0){ if($sum==0) return 0; return round($num*100/$sum+0.00000001,$dec); } Maxim Maletsky maxim@maxim.cx