[PHP] Simple percentage calculator

Post all your tuts or request for tuts here.
Post Reply
User avatar
kaos78414
Posts: 507
Joined: Thu Jul 22, 2010 5:36 am

[PHP] Simple percentage calculator

Post 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!
w00t
User avatar
Last Known Hero
Posts: 807
Joined: Wed Aug 26, 2009 12:28 am

Re: [PHP] Simple percentage calculator

Post by Last Known Hero »

Thanks for the contribution. I'm sure someone here will be able to use it :)
Image
Power3DArt

-Current Project: Fault [Pre-Alpha]
User avatar
Chris
Posts: 1581
Joined: Wed Sep 30, 2009 7:22 pm

Re: [PHP] Simple percentage calculator

Post 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);
}
 
Fighting for peace is declaring war on war. If you want peace be peaceful.
User avatar
kaos78414
Posts: 507
Joined: Thu Jul 22, 2010 5:36 am

Re: [PHP] Simple percentage calculator

Post by kaos78414 »

Good idea. Definitely improves this function. :D

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

Return to “Tutorials”