In PHP, you can use the following method to get the percentage of two numbers.
First, we need to clarify the values of the two numbers, and we can use variables to store these values.
$numerator = 20; // 分子 $denominator = 100; // 分母
Next, we can calculate the percentage using the following code:
$percentage = ($numerator / $denominator) * 100;
In this example, first we divide the numerator by the denominator and then multiply the result by 100. This calculates the percentage of two numbers.
Finally, we can convert the result to a string and output:
echo "分子为 $numerator,分母为 $denominator,百分比为 " . round($percentage, 2) . "%。";
In this example, we use the round()
function to round the result to two decimal places Bit. You can change it yourself as needed.
The following is a complete sample code:
$numerator = 20; // 分子 $denominator = 100; // 分母 $percentage = ($numerator / $denominator) * 100; echo "分子为 $numerator,分母为 $denominator,百分比为 " . round($percentage, 2) . "%。";
Run this code, you will get the following output:
分子为 20,分母为 100,百分比为 20%。
Of course, you can also encapsulate variables and calculation processes into function for easy reuse later. For example:
function getPercentage($numerator, $denominator) { $percentage = ($numerator / $denominator) * 100; return round($percentage, 2); } $numerator = 20; // 分子 $denominator = 100; // 分母 echo "分子为 $numerator,分母为 $denominator,百分比为 " . getPercentage($numerator, $denominator) . "%。";
In this way, you only need to call this function every time you calculate the percentage.
In short, it is very simple to calculate the percentage between two numbers using PHP. Remember to encapsulate it into a function as needed to facilitate future use.
The above is the detailed content of How to divide two numbers and get the percentage in PHP. For more information, please follow other related articles on the PHP Chinese website!