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;
Related
I'm having trouble calculating the discount of total order amount of products that is multiplied by 100.
In my database I'm saving the product price multiplied by 100 e.g.: $price = 33.5 * 100 I'm doing this to prevent wrong calculation of the decimal point .5 when retrieving the data and adding those to other products.
So I have this for now
$test_product_price = 10000 // actual price is 100 because it's save multiplied by 100
$quantity = 3;
$discount = 10.5%;
$order_amount = $test_product_price * 3 // will produce 30000 but actual price is 300 when divided by 100
Now what I want is deduct the $discount which is 10.5%
for actual amount this is working fine
$discounted_amount = 300 - (300 * (10.5 / 100)); // will produce 268.5
but how can I do that on my end that is my amounts are multiplied by 100
Possibly a bit long winded but accurate;
<?php
$amount = 100;
$number = 3;
$percent = 10.5;
$subtotal = $amount * $number;
$discount = ($percent / 100) * $subtotal;
$total = $subtotal - $discount;
$total = number_format((float)$total, 2, '.', '');
echo $total;
?>
I'm trying to do some calculations on getting the total points used in a requested amount of money based on the amount per points.
Kindly refer to below code:
<?php
$amount_perpoints = bcdiv(622.9106666666667,1,2); // AMOUNT OF MONEY PER POINTS
$request_amount = 3114.55; //REQUESTED AMOUNT OF POINTS
$points = 0; // THIS WILL CONTAIN THE TOTAL POINTS
$total_amount = 0; // THIS WILL INCREMENT ACCORDING TO THE PRODUCT OF THE CURRENT POINT AND AMOUNT PER POINTS
while($total_amount < $request_amount){
$points = $points+0.50; //POINTS INCREMENTING BY 0.5
$total_amount = $points * $amount_perpoints;
}
echo $points;
?>
Output: 5.50
Above scenario outputs 5.50 but I believe it should only be 5.00. At 5.00 points of the iteration, $total_amount and $request_amount has already same value of 3114.55. Why does the while loop still satisfies even the two values of the comparing variables are not less than BUT EQUAL?
Your are comparing float numbers. Try to use
while (bccomp($total_amount, $request_amount) === -1) {
I think #jeff is right:
$amount_perpoints = bcdiv(622.9106666666667,1,2); // AMOUNT OF MONEY PER POINTS
$request_amount = 3114.55; //REQUESTED AMOUNT OF POINTS
$points = 0; // THIS WILL CONTAIN THE TOTAL POINTS
$total_amount = 0; // THIS WILL INCREMENT ACCORDING TO THE PRODUCT OF THE CURRENT POINT AND AMOUNT PER POINTS
while($total_amount <= $request_amount){
$points = $points+0.50; //POINTS INCREMENTING BY 0.5
$total_amount = $points * $amount_perpoints;
}
echo $points;
Since you count untill it reach the desired point it sould be less OR equal. It give the output of : 5.5
<?php
$amount_perpoints = bcdiv(622.9106666666667,1,2); // AMOUNT OF MONEY PER POINTS
$request_amount = 3114.55; //REQUESTED AMOUNT OF POINTS
$points = 0; // THIS WILL CONTAIN THE TOTAL POINTS
$new_points=0;
$total_amount = 0; // THIS WILL INCREMENT ACCORDING TO THE PRODUCT OF THE CURRENT POINT AND AMOUNT PER POINTS
while($total_amount < $request_amount){
$points=$new_points;
$new_points = $new_points+0.50; //POINTS INCREMENTING BY 0.5
$total_amount = $new_points * $amount_perpoints;
}
echo $points;
?>
Errors occur when calculating with fractional fractions as a float. Float cannot represent certain decimal numbers exactly. Use only the BC Math functions for such calculations. You don't need a loop either.
$amount_perpoints = "622.91"; // AMOUNT OF MONEY PER POINTS
$request_amount = "3114.55"; //REQUESTED AMOUNT OF POINTS for result 5.0
//$request_amount = "3426.005"; //REQUESTED AMOUNT OF POINTS for result 5.5
$point_step = "0.50";
//calculation
$points = bcdiv($request_amount,$point_step,2);
$points = bcdiv($points,$amount_perpoints,0);
$points = bcmul($points,$point_step,1);
//output
var_dump($points); //string(3) "5.0"
I tried asking this earlier, but I don't think I phrased the question correctly so I worked out something that got me the result I was after and now am hoping that it will help someone help me.
Problem: I have 10 items. If you buy 1, it's $10. I will sell you the second one for $9. I will sell you the third item for $8. I will keep taking off money until we get to $5/item because that is the lowest I will sell it for. So, if you buy all 10, it will cost you $65.
This is the pricing model I am trying to achieve, except at a much larger scale. Instead of a handful of items using dollars, I'm talking about up to millions and using fractions of pennies.
This is my current code:
<?php
function getCost($num_items)
{
$min_price = 0.002;
$max_price = 0.007;
$discount_range = 1000000;
$discount_per_additional_item = ($max_price - $min_price) / ($discount_range - 1);
$price_per_unit = MAX($min_price, ($max_price - ($num_items - 1) * $discount_per_additional_item) );
return $price_per_unit;
}
$array = [100, 1000, 10000, 100000, 200000, 300000, 400000, 500000, 600000, 700000, 800000, 900000, 1000000];
foreach ($array as $value)
{
$sum = 0;
for ($i = 0; $i < $value; ++$i)
$sum += getCost($i);
echo number_format($value) . ' | $' . number_format($sum) . "\n";
}
Which results in:
100 | $1
1,000 | $7
10,000 | $70
100,000 | $675
200,000 | $1,300
300,000 | $1,875
400,000 | $2,400
500,000 | $2,875
600,000 | $3,300
700,000 | $3,675
800,000 | $4,000
900,000 | $4,275
1,000,000 | $4,500
I'm using $array as a sanity check where in the real world, I would simply calculate for the actual number the customer is being charged for.
My question is: Is there a way to accomplish this without using a for loop? Something, perhaps, more elegant?
I made an example online: http://sandbox.onlinephpfunctions.com/code/47e270dbad8cbe16c9ea906ffd2dce098a52fbca
This code will have the same output, and does not have the inner loop:
$min_price = 0.002;
$max_price = 0.007;
$discount_range = 1000000;
$discount_per_additional_item = ($max_price - $min_price)/($discount_range - 1);
$num_progressively_discounted_items =
ceil(($max_price - $min_price) / $discount_per_additional_item);
foreach ($array as $value) {
$num_items_above_min = min($value, $num_progressively_discounted_items);
$num_items_at_min = $value - $num_items_above_min;
$sum = $num_items_at_min * $min_price +
$num_items_above_min * $max_price -
$discount_per_additional_item
* $num_items_above_min * ($num_items_above_min - 1)/2;
echo number_format($value) . ' | $' . number_format($sum) . "\n";
}
This is what it does:
It first checks how many times the unit discount can be subtracted from the original price before hitting the minimum price. If more than the number of items you are buying, then this calculated figure is corrected to that number of items.
The remaining number of items (if any) are also taken note of: these will all have the minimum price.
The sum consists of two parts. The easy part is represented by the number of items that will go for the minimum price, and it is a simple multiplication.
The second part of the sum consists of an always decreasing term, or otherwise put: it is the maximum price for the number of items that don't go for the minimum price, minus the sum of 0+1+2+3+4+5...+n. For that the formula is known: n(n-1)/2.
Like I mentioned in comments, there is something strange in your code: for $i=0 the value returned by getCost($i) is higher than the max price, as the unit discount gets added to it. This can be corrected by starting your inner loop with $i=1. Anyway, this means there is a tiny difference in the result of my proposed code, as it does not have this peculiarity. But as the discount per unit is so tiny, you don't actually notice it in the printed output.
You can do this a little bit more functional style:
function sumOfNaturalSeries($n)
{
return ((1 + $n) / 2) * $n;
}
$minPrice = 0.002;
$maxPrice = 0.007;
$discountRange = 1000000;
$discountStep = ($maxPrice - $minPrice) / $discountRange;
$getPrice = function ($numberOfItems) use (
$minPrice,
$maxPrice,
$discountRange,
$discountStep
) {
if ($numberOfItems <= $discountRange) {
return $maxPrice * $numberOfItems - sumOfNaturalSeries($numberOfItems - 1) * $discountStep;
}
$itemsAboveRange = $numberOfItems - $discountRange;
return $maxPrice * $discountRange - sumOfNaturalSeries($discountRange - 1) * $discountStep + $minPrice * $itemsAboveRange;
};
$array = [100, 1000, 10000, 100000, 200000, 300000, 400000, 500000, 600000, 700000, 800000, 900000, 1000000];
$sums = array_map($getPrice, $array);
var_dump($sums);
var_dump(array_map('number_format', $sums));
Here is demo.
Take a notice on computational error.
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.
I have a requirement where users are forced to choose the multiple of (n) quantity of a product.
The (n) value is set with each product that can be any number.
customer can only purchase the quantity of product in the multiple of (n) quantity set with product.
Suppose if (n) is 5 and user entered quantity as 4 and says Add to Cart. I have to add quantity of that product as 5 automatically.
and if user entered 6 as quantity then I have to add the 10 quantity of that product.
How I go about that?
I am not getting what logic should be applied here.
$entered_quantity = 6;
$suppose_n = 5;
$quantity = ceil($entered_quantity / $suppose_n) * $suppose_n;
echo $quantity;
prints 10
that's not php specific;
what you wonna do is to compute.
ceiling(q / n) * n
where q is the user's quantity,
n is the multiplicity
You could try getting the remainder of the number when dividing by the given n
e.g.:
$n = 5;
$amount = 6; // This would be the input, so replace the 6 with a $_POST/$_GET/etc.
$batches = floor($amount / $n);
$rest = $amount % $n;
if ($rest > 0) {
$batches += 1;
// You could give the user feedback here that they didn't put in a full multiple of $n
}
// $batches now contains the right amount of batches, so to get the total:
$total = $batches * $n;
Ofcourse this can be condensed a lot, but this might give a better overview of what happens :).
Try the below function.
function getNextMultipleOfFive($n) {
$tmp=explode('.',($n/5));
if($tmp[1]) {
return ($tmp[0]+1)*5;
}
return $tmp[0]*5;
}
With a do...while loop:
$q = 6; // quantity by user input
$n = 5; // per purchace amount
$i = 0;
if ($q > 0)
{
do
{
$i += $n;
}
while ($i <= $q);
}
echo $i; // 10
Note: not very effective if $q >> $n