Good day, below is a piece of code that increments the total cost for each product in the session array. My problem is displaying 0 at the end of the total when the last peny = 0.
Example 1, 2.20 + 2.20 = 4.40 but only 4.4 is shown
Example 2, 2.20 + 2.25 = 4.45 and 4.45 is shown
$total = 0;
if (isset($_SESSION['cartItems'])){
foreach ($_SESSION['cartItems'] as $product){
$total += $product['cost'];
}
}
echo $total;
Any advice on how to show/include when a 0 is entered?
This was already answered in a comment by WebCode.ie but here is a detailed answer that may help those facing the same problem:
To customize a number format, you can use the PHP Function string number_format() , that accepts either one, two, or four parameters, this way:
$my_number=25200;
$number_decimals=2;
$dec_separator=".";
$thousands_separator=" ";
echo number_format($my_number , $number_decimals, $dec_separator, $thousands_separator);
// This will output 25 200.00
The number you want to format
The number of decimals
The decimal separator
The thousands separator
Please also note that you can only use 1, 2 or 4 parameters.
Related
Let's say I have 2 numbers like so
1.50
2.00
I want to format the number so that
1.50 will show as 1.5
2.00 will show as 2
Basically if it is not a whole number then show that with ending 0's removed and if it is a whole number to show whole. I was trying number_format('2.00', 2); but that of course keeps the decimals. I was hoping there was a easy way to do this.
Multiply the number with 1 and it will remove any trailing zeros.
$arr = ["1.50","2.00"];
foreach($arr as $v){
echo $v*1 . PHP_EOL;
}
//1.5
//2
Try casting both strings to floats:
echo (float)'1.50';
// => 1.5
echo (float)'2.00';
// => 2
Try it online!
I have a form with two input fields:
Parts Price and
Parts Quantity
And user can click a button to add as many as they want.
I need to calculate the parts * the quantity to get a sum. For example, if the user has Part one which is 10 dollars and has a quantity of 2. The second part is 20 dollars with the quantity of 2, the sum should be 60 dollars.
Part 1 * Quantity = sum of part 1
Part 2 * Quantity = sum of part 2
Sum of part 1 + Sum of part 2
This is a simple math equation but i get confused when it comes to arrays.
I tried the following but it only works right if the quantity is 1:
$sumofparts = array_sum($_POST['partsprice']) * array_sum($_POST['partsquantity']);
When i try the code with a part with the price of 10 dollars and a quantity of 2 and another part is 10 dollars with the quantity of 2 the sum should be 40; however I'm getting a sum of 80
Your math is wrong. What you need is to sum results of multiplying and not multiply sums. In a simple way it can be done like:
$sum = 0;
foreach ($_POST['partsprice'] as $k => $v) {
$sum += $v * $_POST['partsquantity'][$k];
}
echo $sum;
I'm working on a shipping module for wine, and was wondering if anyone could give me a hand - basically:
The wine can be shipped in cases of 8, 12 or 15 bottles, each with its own price. The module needs to take the total number of bottles in the order, and work out which combination of cases gives the lowest price. Eg in an order of 31 bottles, the lowest price works out to 1 case of 15 and two cases of 8, (rather than 2 cases of 15 and 1 of 8, or 2 of 12 and one of 8). Currently, I have the following, which almost works, but misses a few possible combinations
foreach ($rates as $case_size => $case_price)
{
$price = floor($total_bottles / $case_size) * $case_price;
$rem = $total_bottles % $case_size;
if($rem > 12)
{
//needs to use another case of 15
$price = $price + $rates[15];
}
elseif($rem > 8)
{
//needs an extra case of 12
$price = $price + $rates[12];
}
elseif($rem > 0)
{
//needs an extra case of 8
$price = $price + $rates[8];
}
$quotes[] = $price;
}
return min($quotes);
From your post your saying that the most price-effective system wouldn't just the one that has uses the lowest cost per bottle of the container, but also needs to be the most efficient at filling the containers. However your algorithm is only looking at would use the fewest large boxes possible. You need an algorithm that will completely fill each case possible.
I would do something like this: Use a recursive program to find the combination that would most completely fill each case.
function fit_case($number, $case_size) {
$rem = $number % $case_size;
$next_size=magic_voodo0();
if($rem==0) { //if perfectly fills it you're done
return ($number/$case_size)*$rates[$case_size];
} else if(($rem % $next_size)/$next_size>.5) {
//if over 50% fills the next case add the next smaller case
return floor($number/$case_size)*$rates[$case_size]+fit_case($rem, $next_size);
} else { //otherwise back off 1 of the biggest cases, and fill the rest
return (floor($number/$case_size)-1)*$rates[$case_size]+fit_case($rem, $next_size);
Hope this helps.
Different approach. Use a lookup table that has all combinations of boxes for a specific number of bottles.
1 bottle - 8
...
31 bottle - 15-8-8,15-15-8,8-8-8-8, and so on
and so on
Use another lookup table for the different rates per box per country
In your function
get table row for country prices
get the different combinations for the number of bottles
do a foreach loop on combinations
save the price and combination of first loop to variables
compare the price of the next loop with the saved value
if it is lower, save price and combination/if not, continue
loop through all combinations
return lowest price/box combination
This question already has answers here:
How to deal with the sum of rounded percentage not being 100?
(5 answers)
Closed 9 years ago.
I have created a php program where user can can vote on polls and after that, the poll result will displayed with only percentage, however I am facing an error in my program. Code which I am using for percentage calculation is <?php echo round(($num_votes / $total_votes) * 100) ?>
Now If we talk about a sample poll result, assume we have five options
option A - 4 votes
option B - 2 votes
option C - 4 votes
option D - 1 votes
option E - 0 votes
Total votes = 11
In this scenario the percentage result generating is
option A - 36%
option B - 18%
option C - 36%
option D - 9%
option E - 0%But the total of percentage is 99% instead of 100%. What I want is total should always be 100% Any help would be appreciated
Thanks.
If you are working with rounded numbers, you can indeed end up with...rounded numbers. And the sum of those rounded numbers will be different from the regular sum. There's little you can do to change that. If you insist, you'd have to:
calculate the rounded numbers
calculate the sum, and if not 100%,
loop through the rounded numbers and decide which one should get the missing percent.
But you're messing with the data. You may think you're cleaning it, but you're messing it up.
This way lead to ~100%, 'number_format' is nice thing
$a = 4;
$b = 2;
$c = 4;
$d = 1;
$e = 0;
$total = $a + $b + $c + $d + $e;
$arr = array(
'a' => number_format(($a / $total) * 100, 3),
'b' => number_format(($b / $total) * 100, 3),
'c' => number_format(($c / $total) * 100, 3),
'd' => number_format(($d / $total) * 100, 3),
'e' => number_format(($e / $total) * 100, 3)
);
foreach ($arr as $answer => $percentage) {
echo $answer .': '. $percentage . '<br />';
}
// this will be 100.001 so we format is
echo 'total: '. number_format(array_sum($arr), 2);
You can specify number of digits after decimal places in round.
ex:round(number,2);
There's nothing out-of-the-box you can do about it, if you floor() everything you'll miss one point, if you ceil() you'll gain one point.
You could floor() everything then if then calculate the array_sum(), if not 100 then find min() and ceil() it.
I need to total the number of clicks over 10 links on my page and then figure out the percentage of people that clicked each. This is easy division, but how do I make sure that I get a round 100% at the end.
I want to use the below code, but am worried that a situation could arise where the percentages do not tally to 100% as this function simply removes the numbers after the period.
function percent($num_amount, $num_total) {
$count1 = $num_amount / $num_total;
$count2 = $count1 * 100;
$count = number_format($count2, 0);
echo $count;
}
Any advice would be much appreciated.
Instead of calculating one percentage in your function you could pass all your results as an array and process it as a whole. After calculating all the percentages and rounding them make a check to see if they total 100. If not, then adjust the largest value to force them all to total 100. Adjusting the largest value will make sure your results are skewed as little as possible.
The array in my example would total 100.02 before making the adjustment.
function percent(array $numbers)
{
$result = array();
$total = array_sum($numbers);
foreach($numbers as $key => $number){
$result[$key] = round(($number/$total) * 100, 2);
}
$sum = array_sum($result);//This is 100.02 with my example array.
if(100 !== $sum){
$maxKeys = array_keys($result, max($result));
$result[$maxKeys[0]] = 100 - ($sum - max($result));
}
return $result;
}
$numbers = array(10.2, 22.36, 50.10, 27.9, 95.67, 3.71, 9.733, 4.6, 33.33, 33.33);
$percentages = percent($numbers);
var_dump($percentages);
var_dump(array_sum($percentages));
Output:-
array (size=10)
0 => float 3.51
1 => float 7.69
2 => float 17.22
3 => float 9.59
4 => float 32.86
5 => float 1.28
6 => float 3.35
7 => float 1.58
8 => float 11.46
9 => float 11.46
float 100
This will also work with an associative array as the function parameter. The keys will be preserved.
These figures could now be presented in a table, graph or chart and will always give you a total of 100%;
What you want to do is this.
Total the number of clicks across the board, then divide each number by the total.
For example:
1134
5391
2374
2887
In this case, four buttons, with a total of 11786 clicks, so:
1134 / 11786 = 0.09621....
5391 / 11786 = 0.45740....
2374 / 11786 = 0.20142....
2887 / 11786 = 0.24495....
Then for each division, round the result to 'two decimal points', so the first result:
0.09621.... becomes 0.10
because the 3rd point is 5 or above, it would remain at 0.09 if the 3rd point was below 5.
Once you have all of the results rounded, multiply each by 100 then add them up.
The ending result will always be 100.
Should warn you however that depending on how you use each individual percentage, when you round them, any result less that 0.05 will become 0%, unless you keep the value before you round it so you can declare it as a percentage less than 1.
I think you want to use ceil() or round() .
Since these are floating point numbers, there is room for error. Be careful how you round, and be sure that you don't independently calculate the last remaining percentages. Simply subtract the total of what you have from 1 or 100.
Make sure you dont calculate separate sides of the equation, sum one side, then subtract the other from 1 or 100 or however you are handling your percentages.
I run into this quite a bit and have a hack for it.
$percentages = array(
'1' => 87.5,
'2' => 12.5,
'3' => 0,
'4' => 0,
'5' => 0
);
If you round those percentages for output, you will end up with 88% and 13% (101%)
round($percentages['1']);
round($percentages['2']);
// 88
// 13
So here is the code I use to fix it.
$checkTotal = array_sum($percentages);
$max = max(array_keys($percentages));
if ($checkTotal > 100) {
$percentages[$max] = $percentages[$max] - 1;
}
if ($checkTotal < 100) {
$percentages[$max] = $percentages[$max] + 1;
}
If it is 100, do nothing.
If it is less than 100, add 1 to equal 100
If it is over 100, subtract 1 to equal 100