Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Percentage a Number is of Another Number

Tags:

php

math

How to find the percentage a number is of another number in PHP?

Example

$num1 = 2.6;
$num2 = 2.6;
// Should equal to 100%
like image 501
user969729 Avatar asked Nov 25 '11 00:11

user969729


2 Answers

Divide the two numbers and multiply by 100 to get the percentage:

$percentage = ($num1 / $num2) * 100;
echo $percentage . "%";

Of course you will need to check so that $num1 is not 0, something like this: $percentage = ($num1 !== 0 ? ($num1 / $num2) : 0) * 100;

like image 128
Cyclonecode Avatar answered Nov 11 '22 12:11

Cyclonecode


$percentage = sprintf("%d%%", $num1 / $num2 * 100); // string: 100%
like image 40
Tim Cooper Avatar answered Nov 11 '22 14:11

Tim Cooper