73

I would like to calculate, in PHP, the percentage of a number. For example:

$percentage = 50;
$totalWidth = 350;

For this example, 50% of 350 = 175

How can I do that?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
John Smeuth
  • 805
  • 1
  • 7
  • 7

2 Answers2

195
$percentage = 50;
$totalWidth = 350;

$new_width = ($percentage / 100) * $totalWidth;
Joundill
  • 6,828
  • 12
  • 36
  • 50
pogeybait
  • 3,065
  • 2
  • 21
  • 23
26

Divide $percentage by 100 and multiply to $totalWidth. Simple maths.

hkf
  • 4,440
  • 1
  • 30
  • 44
  • in case the type is an integer it is better if you multiply first, then divide by 100. Example when dividing first: int answer = 50/100 = 0.5 (int rounds 0.5 to 1); answer*width = 1*350 = 350. D'oh. – Ozzy Apr 18 '12 at 00:37
  • 2
    @Ozzy Types don't matter here. If a calculation results in a fraction, the result will automatically be a float and won't be rounded. – deceze Apr 18 '12 at 01:12