Percentage of a number from another number

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

Example

$num1 = 2.6; $num2 = 2.6; // Should equal to 100% 
+6
source share
2 answers

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

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

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

+17
source
 $percentage = sprintf("%d%%", $num1 / $num2 * 100); // string: 100% 
+9
source

Source: https://habr.com/ru/post/902342/


All Articles