Page 1 of 1

[PHP] Simple percentage calculator

Posted: Tue Jul 27, 2010 10:00 pm
by kaos78414
So I've written a math helper to help me out with some of the calculations needed for the PBBG I'm making, but this function is pretty helpful for anyone as it can help you to calculate percentage of HP, MP or what have you. (I'm not sure if you've already been over this in the tutorials, as I haven't gone through them all, but it could be useful nonetheless)

Here's the code: (file called math_helper.php)

Code: Select all

if ( ! function_exists('percentage'))
{
	function percentage($min, $max)
	{
		$count1 = $min / $max;
		$count2 = $count1 * 100;
		$count = number_format($count2, 0);
		return $count;
	}
}

Usage example:

Code: Select all

include 'math_helper.php'

$maxhp = '15';
$current_hp = '10';

echo '<div style="width: 110px;background-color:red;">';
echo '<div style="width:'.percentage($current_hp, $maxhp).'%; background-color: green">';
echo $current_hp.'/'.$maxhp.'</div></div>';
Anyway, hope someone finds it useful!

Re: [PHP] Simple percentage calculator

Posted: Sun Aug 01, 2010 5:41 pm
by Last Known Hero
Thanks for the contribution. I'm sure someone here will be able to use it :)

Re: [PHP] Simple percentage calculator

Posted: Fri Aug 06, 2010 10:31 am
by Chris
Too save memory you could leave out the use of not needed variables which will make the function even simpler.

Code: Select all

function percentage($min, $max)
{
    return number_format(((min/max)*100), 0);
}
 

Re: [PHP] Simple percentage calculator

Posted: Fri Aug 06, 2010 8:08 pm
by kaos78414
Good idea. Definitely improves this function. :D

And that's why two brains are better than one :P