How To Calculate The Percentage Of A Number Using PHP?
This is a short guide on how to calculate the percentage of a given number in PHP. For example: What is 25% of 100? Or what is 10% of 728?
In this code snippet, I have put each calculation on its own separate line, just to make the math a little clearer:
1. We used the number 928 for example purposes.
2. We specified that we wanted to get 25% of 928.
3. We converted our percentage value into a decimal number by dividing it by 100. This turns 25 into 0.25.
4. We then multiplied 0.25 by 928.
5. The end result is 232, which means that 25% of 928 is 232.
Function
If you're looking for a simple PHP function to use in your projects, then you can use the following:
Source: PHP: Calculate The Percentage Of A Number.
In this code snippet, I have put each calculation on its own separate line, just to make the math a little clearer:
<?php //My number is 928. $myNumber = 928; //I want to get 25% of 928. $percentToGet = 25; //Convert our percentage value into a decimal. $percentInDecimal = $percentToGet / 100; //Get the result. $percent = $percentInDecimal * $myNumber; //Print it out - Result is 232. echo $percent;A quick summary of what we did:
1. We used the number 928 for example purposes.
2. We specified that we wanted to get 25% of 928.
3. We converted our percentage value into a decimal number by dividing it by 100. This turns 25 into 0.25.
4. We then multiplied 0.25 by 928.
5. The end result is 232, which means that 25% of 928 is 232.
Function
If you're looking for a simple PHP function to use in your projects, then you can use the following:
/** * A simple PHP function that calculates the percentage of a given number. * * @param int $number The number you want a percentage of. * @param int $percent The percentage that you want to calculate. * @return int The final result. */ function getPercentOfNumber($number, $percent){ return ($percent / 100) * $number; } echo getPercentOfNumber(928, 25); //output 232
Source: PHP: Calculate The Percentage Of A Number.
great
ReplyDelete