PHP calculate percentages - php

I need some help. It's a simple code, but I don't have idea how to write in down. I have the numbers:
$NumberOne = 500;
$NumberTwo = 430;
$NumberThree = 150;
$NumberFour = 30;
At all this is:
$Everything = 1110; // all added
Now I want to show what percentage is for example $NumberFour of everything or what percentage is $NumberTwo of $Everything. So the "market share".

Use some simple maths: divide the number you wish to find the percentage for by the total and multiply by 100.
Example:
$total = 250;
$portion = 50;
$percentage = ($portion / $total) * 100; // 20
Solution to original example
To get $NumberFour as a percentage of the total amount you'd use:
$percentage = ($NumberFour / $Everything) * 100;
Rounding
Depending on the numbers you're working with, you may want to round the resulting percentage. In my initial example, we get 20% which is a nice round number. The original question however uses 1110 as the total and 30 as the number to calculate the percentage for (2.70270...).
PHP's built in round() function could be useful when working with percentages for display: https://www.php.net/manual/en/function.round.php
echo round($percentage, 2) . '%'; // 2.7% -- (30 / 1110) * 100 rounded to 2dp
Helper Functions
I would only contemplate creating helper functions when their use justifies it (if calculating and displaying a percentage isn't a one-off). I've attached an example below tying together everything from above.
function format_percentage($percentage, $precision = 2) {
return round($percentage, $precision) . '%';
}
function calculate_percentage($number, $total) {
// Can't divide by zero so let's catch that early.
if ($total == 0) {
return 0;
}
return ($number / $total) * 100;
}
function calculate_percentage_for_display($number, $total) {
return format_percentage(calculate_percentage($number, $total));
}
echo calculate_percentage_for_display(50, 250); // 20%
echo calculate_percentage_for_display(30, 1110); // 2.7%
echo calculate_percentage_for_display(75, 190); // 39.47%

Create function to calculate percentage between two numbers.
<?php
/**
* Calculate percetage between the numbers
*/
function percentageOf( $number, $everything, $decimals = 2 ){
return round( $number / $everything * 100, $decimals );
}
$numbers = array( 500, 430, 150, 30 );
$everything = array_sum( $numbers );
echo 'First of everything: '.percentageOf( $numbers[0], $everything )."%\n";
echo 'Second of everything: '.percentageOf( $numbers[1], $everything )."%\n";
echo 'Third of everything: '.percentageOf( $numbers[2], $everything )."%\n";
echo 'Fourth of everything: '.percentageOf( $numbers[3], $everything )."%\n";
?>
This outputs
First of everything: 45.05%
Second of everything: 38.74%
Third of everything: 13.51%
Fourth of everything: 2.7%

You can also come up with the percentage with the following formula. For the percentage, add a 0. in front of it. So 5% would be 0.05. Total X 0.05 is the amount.

Related

PHP Making a variable increment based on another variable's value without having too much code?

i'm trying to increase a variable value depending on the other variable value for example:
i have a variable called $totalhousesleft...
i want to set a price depending on how many $totalhousesleft i have...
everytime the totalhousesleft is down by 10, i want to increase the variable $currentprice by 1.
the starting value of $totalhouses left is 8000 and every time it goes down by 10, i set the $currentprice +1... the starting value of current price is 9...
something like:
If ($totalhousesleft >= 8000) {$currentprice = 9; $sellingprice = 8;}
If ($totalhousesleft >= 7990) {$currentprice = 10; $sellingprice = 9;}
If ($totalhousesleft >= 7980) {$currentprice = 11; $sellingprice = 10;}
If ($totalhousesleft >= 7970) {$currentprice = 12; $sellingprice = 11;}
ALL THE WAY DOWN UNTIL HOUSES LEFT IS 1. If someone can please show me a loop or a shorter code i would really appreciate it!
#elias-soares answer is close, but is missing ceil...and an explanation.
foreach ( [8000, 7995, 7990, 7985, 7980, 7975, 7970, 7965] as $totalhousesleft ) {
$currentprice = 9 + ((ceil(800 - ((min(8000, $totalhousesleft)) / 10))) * 1);
$sellingprice = $currentprice - 1;
}
Try it here: https://onlinephp.io/c/68196
Let's break down how to get $currentprice:
//$currentprice = ceil(9 + (800 - (min(8000, $totalhousesleft) / 10)));
// get the lesser of 8000, or $totalhousesleft
// in other words, 8000 is the maximum number to calculate
$totalhousesleft = min(8000, $totalhousesleft);
// divide total houses left into number of tenth units
$tenth = $totalhousesleft / 10;
// since the price increases when the number of tenth units decreases,
// the unit factor is the difference between the max possible tenths
// and tenths of the current total houses left
$tenthunit = 800 - $tenth;
// tenth unit is fractional for values not evenly divisible by 10,
// so round up
$tenthroundup = ceil($tenthunit);
// multiply the number of tenth units with the price per unit
$pricepertenth = $tenthroundup * 1; // 1 currency per tenth unit
// add the price per tenth cost to the base cost (9 currency)
$currentprice = 9 + $pricepertenth;
Bonus: this can be implemented in a function:
function getPrices ($totalhousesleft, $baseprice = 9, $discount = 1, $priceperunit = 1, $maxtotal = 8000, $units = 10) {
$currentprice = $baseprice + ((ceil(($maxtotal / $units) - ((min($maxtotal, $totalhousesleft)) / $units))) * $priceperunit);
return [$currentprice, $currentprice - $discount];
}
foreach ( [8000, 7995, 7990, 7985, 7980, 7975, 7970, 7965] as $totalhousesleft ) {
list($currentprice, $sellingprice) = getPrices($totalhousesleft);
}
Try it here: https://onlinephp.io/c/2672b
A for or while loop could be used for this. I'd use for:
$iteration = 0;
for($x = 8000; $x > 0; $x = $x - 10){
if(empty($iteration)) {
$iteration = $x/1000;
}
if ($totalhousesleft >= $x) {
$currentprice = $iteration;
$sellingprice = $currentprice + 1;
break;
}
$iteration++;
}
if(empty($currentprice)){
$currentprice = $iteration;
$sellingprice = $currentprice + 1;
}
This iterates over until a match is found then breaks out of the looping. The prices are based on the iteration it is in.
Demo link: https://3v4l.org/Mm432 (updated for edge cases 0-9)
You can use Math.
$currentprice = 9 + (800 - (min(8000,$totalhousesleft)/10));
$sellingprice = $currentprice - 1;

How to determine every 100 item in a while loop php?

I'm currently learning PHP, and I'm struggling with this:
"For every 100 ordered products in a category, 2% will be deducted:"
This is my code:
$gesA = 309; // (The amount of product)
$gesN = 1011.08; // (The full price of product)
$i = 1;
while($i)
{
if($gesA % 100 == 0)
{
echo $gesN;
echo "<br>";
$gesN = $gesN / 0.2;
}
$i++;
$gesN++;
}
echo $gesN;
Yet, I can't figure it out. Could someone help me?
First you find how many times it is that there are 100 ordered products, which can be calculated by divide the number of products by 100.
$no = $getA / 100;
But that can get you a floating number so you remove the decimal part with floor()
$no = floor($getA / 100);
Then the percentage will be 2% times the integer number.
$deductPercentage = 2 * $no;
And the final product price will be the remaining of the deducted price
$deductedPrice = $gesN * $deductPercentage / 100;
$finalPrice = $gesN - $deductedPrice;

How can I round up from number 621 to 700 in PHP?

$num=621;
echo round(round(621,-2));
Something like this (returns the closest $multiple not less than the given $number):
function round_up($num, $mul) {
return ceil($num / $mul) * $mul;
}
Called like this:
echo round_up(621, 100);
> 700
Works for "weird" quantities, too:
echo round_up(124.53, 0.25);
> 124.75
echo round_up(pi(), 1/7);
> 3.1428571428571
If you want to specify decimal places instead of multiples, you could use the power operator ** to convert decimal places to multiples.
You could do round_down in a similar way using floor.
I think you are trying to round off a number to the nearest 100.
Simply do this by using the ceil function.
ceil(621 / 100) * 100;
You can use ceil function to round any number to its nearest number.
$number = ceil($inputNumber / $nearestNumber) * $nearestNumber;
As an option, subtract the reminder and add 100:
function ceil100($value) {
return $value - $value % 100 + 100;
}
My answer is $numero = $numero + 100 - $numero % 100;
php > $numero = 621;
php > $numero = $numero + 100 - $numero % 100;
php > echo $numero;
700

Round up decimal number for specific decimal places in PHP

I want to round up my variable if it's decimal larger than .3 and if it's lower or equal it will round down, for example if i have 1.34 it will round up to 2, if i have 1.29 it will round down to 1, and if i have 1.3 it will round down to 1. I don't know how to do this precisely, right now i'm using the round basic function like this:
$weight = $weight/1000;
if($weight < 1) $weight = 1;
else $weight = round($weight, 0, PHP_ROUND_HALF_DOWN);
If you manipulate the numbers a bit, you can figure out if the decimals are .3 or higher. You achieve this by flooring the value, and subtract that from the original value. Check if the result of that, multiplied by 10, is greater than 3. If it is, you've got something above x.3.
$number = 1.31;
$int = floor($number);
$float = $number-$int;
if ($float*10 > 3.1)
$result = ceil($number);
else
$result = $int;
echo $result; // 2
Live demo
I made you a little hack, here's the code
$weight = 5088;
$weight = $weight/1000;
if($weight < 1) {
$weight = 1;
} else {
// I get the last number (I treat the $weight as a string here)
$last_number = substr($weight, -1, 1);
// Then I get the precision (floating numbers)
$precision = strlen(substr(strrchr($weight, "."), 1));
// Then I convert it to a string so I can use some helpful string functions
$weight_str = (string) $weight;
// If the last number is less then 3
if ($last_number > 3)
// I change it to 9 I could just change it to 5 and it would work
// because round will round up if then number is 5 or greater
$weight_str[strlen($weight_str) -1] = 9;
}
}
// Then the round will round up if it's 9 or round down if it's 3 or less
$weight = round($weight_str, $precision);
echo $weight;
Maybe something like this function?
function roundImproved($value, $decimalBreakPart = 0.3) {
$whole = floor($value);
$decimal = $value - $whole;
$decimalPartLen = strlen($decimal) - 2;
return (number_format($decimal, $decimalPartLen) <= number_format($decimalBreakPart, $decimalPartLen) ? $whole : ceil($value));
}
Proof:
http://sandbox.onlinephpfunctions.com/code/d75858f175dd819de069a8a05611ac9e7053f07a
You can specify "break part" if you want.

Creating a 5 star product review with PHP

I'm working on a 5 stars products review for a website using php and MySQL, everything works great except my total stars,
When the review is submitted the customer can only add from 1 to 5 stars (no .5) then I'm summing the rating of each review and dividing it by the number of reviews. Now the proble is I need to get either 1, 1.5, 2, 2.5 and so on and sometimes I'll get something like 3.66768748.
How can I round the number so that if it's below if it's more that .5 it will be the ceil, if it's .5 it stays as is and if it's less than .5 it will floor it?
Is there a built in function that I can use for this?
Thank you in advance!
The following function will round to whichever is closest - the next lowest integer, the next highest integer, or the halfway point between them.
function half_star_round($input) {
$frac = $input - floor($input);
if($frac < 0.25) {
return floor($input);
} else if($frac >= 0.75) {
return ceil($input);
} else {
return floor($input) + 0.5;
}
}
This works. Pass the value you want to be rounded to in the second arg. In your case 0.5
function roundTo($value, $roundTo = 1) {
$rounded = round($value); // 4
$roundToComparer = $roundTo / 2;
if ($value < $rounded) { // rounded to ceiling
if (($rounded - $roundToComparer) > $value) {
$rounded = $rounded - $roundTo;
}
} else { // rounded to floor
if (($rounded + $roundToComparer) < $value) {
$rounded = $rounded + $roundTo;
}
}
return $rounded;
}
$rating = 3.66768748;
echo roundTo($rating, 0.5);
Take the sum of the reviews
Divide by the total reviews
Multiply by two
Round
Divide by two
Php proveide round function for that.
http://php.net/manual/en/function.round.php

Categories