My php code not getting add correct - php

I making one counter, I am using PHP and almost everything was going fine but i found one small bug in it.
My first two step on counter is going fine that is $bid and $stax.
My last result $pay should be : 8138 + 814 + 448 = 9400 but it is giving me $9,399
My Output is:
Value $8,138 bid $814 tax $448 You Pay $9,399
Value $8,952 bid $895 tax $492 You Pay $10,339
Value $9,847 bid $985 tax $542 You Pay $11,373
Here is my php
<?php
$i = 0;
$v = 8138; // value : 8138
do {
$i++;
$bid = $v / 10; // output : $814
$ftax = $v + $bid;
$stax = $ftax / 20; // output : tax $448
$pay = $v + $bid + $stax; // 8138 + 814 + 448 = 9400
echo "Value $" . number_format($v) . " bid $" . number_format($bid) . " tax $" . number_format($stax) . " You Pay $" . number_format($pay) . "<br />";
$v = $v * 1.1;
} while ($i <= 2);
?>
Thanks in advance :)

Change your echo line to not drop decimals:
echo "Value $" . $v . " bid $" . $bid . " tax $" . $stax . " You Pay $" . $pay . "<br />";
Value $8138 bid $813.8 tax $447.59 You Pay $9399.39Value $8951.8 bid $895.18 tax $492.349 You Pay $10339.329Value $9846.98 bid $984.698 tax $541.5839 You Pay $11373.2619
So 8138 + 813.8 + 447.59 = 9399.39, which rounds down to 9399.
On the other hand, if you round immediately, 813.8 rounds up to 814 and 447.59 rounds up to 448, but you've just added 0.61 to your calculation before even starting, which obviously results in a higher number (9400).
This is why math and science teachers tell you not to round until the very end, since each time you do it, your answer gets less accurate.

if you dont want to use decimals, round off all division calculations by using round(). Also, multiplications with decimals. See it in action here
$i = 0;
$v = 8138; // value : 8138
do {
$i++;
$bid = round($v / 10); // output : $814
$ftax = $v + $bid;
$stax = round($ftax / 20); // output : tax $448
$pay = $v + $bid + $stax; // 8138 + 814 + 448 = 9400
echo "Value $" . number_format($v) . " bid $" . number_format($bid) . " tax $" . number_format($stax) . " You Pay $" . number_format($pay) . "<br />";
$v = round($v * 1.1);

Lack of casting/decimals be ye problem matey. har har har

Related

How to apply a discount to basket

I'm trying to apply a discount to my basket for each pair of 2 items that cost £1.50 each but I can't seem to get the hang of it. I draw the results from two SQL queries/tables of 'discount' and 'basket' Here's the following I've tried:
$discount_count[] = 0;
$i = 0;
while ($row2 = mysql_fetch_array($data_set2)) {
if ($row['product'] == $row2['product']) {
foreach ($row2 as $current_row) {
$actual_price = $row['product_cost'] * $row2['quantity'];
$discount_total = round(($actual_price - ($actual_price * ($row2['discount_percent'] / 100))), 2);
$total_price = $discount_total / $row2['quantity'] * $row['quantity'];
$product_total = $row['product_cost'] * $row['quantity'];
if ($i % 2 && $total_price * $row2['quantity'] > $row['product_cost'] * $row2['quantity']){
echo "<br /><br />actual price per 2: £" . $actual_price;
echo "<br />discount total: £" . $discount_total;
echo "<br />actual minus discount: £";
echo $actual_price - $discount_total;
echo "<br />total price: £" . $total_price;
echo "<br />product cost: £" . $product_total;
$discount_count[] = $actual_price - $discount_total;
}
$i++;
}
}
}

How do I divide an integer over multiple values in PHP?

I'm trying to make a little PHP script for fun, and I'm a little stuck.
I want to divide an integer (for example 5) over multiple values.
For example:
$total = 5;
$mike = 0;
$ralf = 0;
$ashley = 0;
// Run the magic here
echo "Mike has " . $mike . " apples, Ralf has " . $ralf ." apples and Ashley has " . $ashley . " apples";
The output that I expect would look something like this:
Mike has 2 apples, Ralf has 1 apples and Ashley has 2 apples
Is there a way how to do this? :)
I can't do this hard coded, because I want the values to be randomized.
Cheers
Do it like this:
$total = 5;
$mike = rand(1,$total-2); // so that max value is 3 (everyone should get at least 1) ($total - $numberOfVarsToDistributeTheValueTo + 1)
$ralf = rand(1,$total - $mike - 1); // if 3 goes to mike, only 1 goes to ralf
$ashley = $total - $mike - $ralf; // i hope you understand.
// use it.
Something like this would work:
$people = array('mike','ralf','ashley');
$num = count($people);
$sum = 5; // TOTAL SUM TO DIVIDE
$groups = array();
$group = 0;
while(array_sum($groups) != $sum) {
$groups[$group] = mt_rand(0, $sum/mt_rand(1,5));
if(++$group == $num){
$group = 0;
}
}
// COMBINE ARRAY KEYS WITH VALUES
$total = array_combine($people, $groups);
echo "Mike has " . $total['mike'] . " apples, Ralf has " . $total['ralf'] ." apples and Ashley has " . $total['ashley'] . " apples";
Solution is inspired from this answer: https://stackoverflow.com/a/7289357/1363190
Hope This function will do your work . it can work for variable # of persons also.
divide_items(10,['mike','ralf','ashley']);
function divide_items($total=1,array $persons){
$progressed = 0;
for($i=0;$i<count($persons);$i++){
echo $random_count = rand(1,$total);
if(($i==(count($persons)-1)) && $progressed<$total ){
$random_count1 =$total - $progressed;
echo $persons[$i]." has ".$random_count1 ." Items<br>";
continue;
}
$progressed = $progressed+$random_count;
if($progressed<=$total){
echo $persons[$i]." has ".$random_count ." Items<br>";
}else{
echo $persons[$i]." has 0 Item<br>";
}
$total = $total-$random_count;
$progressed = 0;
}
}

Change Excel Circular Dependency into PHP

I deleted a question I posted earlier because I oversimplified the example, and got more flak for problems there, so have decided to post the whole problem here instead.
The Task
Much like this question here...Copying Excel's Circular Reference formula in PHP I am trying to change an Excel Circular reference into PHP.
Most of my frustration is not knowing the correct terms to google this for myself.
The Situation
I have converted all logic in the following spreadsheet into PHP below...
<?php
$vat = '1.2';
$mileage = 10;
$price = 6250.00;
$contract_term = 24;
$deposit_months = 6;
$otr_price = 9409.00;
$discount = 0;
$lom_a = 36.08;
$lom_b = 5.14;
$vehicletype = "Car";
$first_reg_fee = 55.00;
$emission_price = 30.00;
$fees = 21.03;
$margin = 50.00;
if (!empty($discount)) {
$discounted_otr_percent = (int)$discount/100;
$discounted_otr_amount = $discounted_otr_percent * $otr_price;
$discounted_otr = $otr_price-$discounted_otr_amount;
} else {
$discounted_otr = $otr_price;
}
$totaltobefunded = ($discounted_otr - $first_reg_fee - 0 /* Emissions */) / $vat;
print '<hr><p>Total to be Funded: <strong>' . $totaltobefunded . '</strong></p>';
$vatbal = $discounted_otr - $first_reg_fee - 0 /* Emissions */ - $totaltobefunded;
print '<p>VAT: <strong>' . $vatbal . '</strong></p>';
if($vehicletype == "Car") {
$balloon = $price / $vat * 0.9;
} else {
$balloon = $price * 0.9;
}
print '<p>CAP 90% price: <strong>' . $balloon . '</strong></p>';
$totalamountborrowed = $totaltobefunded - $balloon;
print '<p>Total Amount Borrowed: <strong>' . $totalamountborrowed . '</strong></p>';
$fundingrental = $totalamountborrowed * $lom_a / 1000;
print '<p>Funding Rental: <strong>' . $fundingrental . '</strong></p>';
$balloonrental = $balloon * $lom_b / 1000;
print '<p>Funding Rental: <strong>' . $balloonrental . '</strong></p>';
$monthlyfinancerental = $fundingrental + $balloonrental;
print '<p>Monthly Finance Rental: <strong>' . $monthlyfinancerental . '</strong></p>';
$monthlyrentalwithfees = $monthlyfinancerental + $fees;
print '<p>Monthly Finance Rental With Fees: <strong>' . $monthlyrentalwithfees . '</strong></p>';
$totalmargin = $margin * $contract_term;
print '<p>Total Margin: <strong>' . $totalmargin . '</strong></p>';
$totalrentalandfees = $monthlyrentalwithfees * ($contract_term + $deposit_months -1);
print '<p>Total Rental and Fees: <strong>' . $totalrentalandfees . '</strong></p>';
$totalcontractcost = $totalmargin + $totalrentalandfees;
print '<p>Total Contract Cost: <strong>' . $totalcontractcost . '</strong></p>';
$actualmonthlyrental = $totalcontractcost / ($contract_term + $deposit_months -1);
print '<p>Actual Monthly Rental: <strong>' . $actualmonthlyrental . '</strong></p>';
$deposit = $actualmonthlyrental * $deposit_months;
print '<p>Deposit: <strong>' . $deposit . '</strong></p>';
In the PHP code above, I have hard coded all of the variables for the time being just to get this working. In the real life example, these will change for each vehicle.
A Circular Reference exists between N19 (Total to be funded) , N34 (Actual Monthly Rental) and N36 (Deposit).
So at some point before, during, or after the FOR statement, there needs to be...
$totaltobefunded = $totaltobefunded - $deposit;
What I have tried
I have tried using the PHP for from the linked question on my example, but it just keeps taking away the deposit from the Total to be funded, and I am left with minus numbers.
In the example in the link, it has the following results...
1410
1211.19
1239.22221
1235.26966839
1235.826976757
1235.7483962773
1235.7594761249
1235.7579138664
1235.7581341448
1235.7581030856
1235.7581074649
1235.7581068474
This refines the number to the best possible outcome, and this is what I am trying to achieve. Just like my Excel document.
At the moment, my PHP prints out....
Total to be Funded: 7795
VAT: 1559
CAP 90% price: 4687.5
Total Amount Borrowed: 3107.5
Funding Rental: 112.1186
Funding Rental: 24.09375
Monthly Finance Rental: 136.21235
Monthly Finance Rental With Fees: 157.24235
Total Margin: 1200
Total Rental and Fees: 4560.02815
Total Contract Cost: 5760.02815
Actual Monthly Rental: 198.62166034483
Deposit: 1191.729962069
What I need help with
Using the PHP code above (which I have over simplified for this question btw), where should I put my "for" statement in order to correctly loop through the 3 numbers in the circular reference to get the result Im after?
As you can see in the Excel Screenshot, the target numbers are...
Total to be Funded: 6815.32
VAT: 2538.68
CAP 90% price: 4687.5
Total Amount Borrowed: 2127.82
Funding Rental: 76.7717456
Funding Rental: 24.09375
Monthly Finance Rental: 100.8654956
Monthly Finance Rental With Fees: 121.8954956
Total Margin: 1200
Total Rental and Fees: 3534.9693724
Total Contract Cost: 4734.9693724
Actual Monthly Rental: 163.27480594483
Deposit: 979.64883566897
I hope this makes sense to someone and they can assist. I'll answer any questions as best as I can.
The solution in PHP is as follows....
<?php
$vat = '1.2';
$mileage = 10;
$price = 6250.00;
$contract_term = 24;
$deposit_months = 6;
$otr_price = 9409.00;
$discount = 0;
$lom_a = 36.08;
$lom_b = 5.14;
$vehicletype = "Car";
$first_reg_fee = 55.00;
$emission_price = 30.00;
$fees = 21.03;
$margin = 50.00;
$deposit = 0;
if (!empty($discount)) {
$discounted_otr_percent = (int)$discount/100;
$discounted_otr_amount = $discounted_otr_percent * $otr_price;
$discounted_otr = $otr_price-$discounted_otr_amount;
} else {
$discounted_otr = $otr_price;
}
$max_iter = 100;
$max_change = 0.001;
$prev_target_val = PHP_INT_MAX;
$totaltobefunded = 0;
$crt_iter = 0;
while(($crt_iter < $max_iter) && (abs($prev_target_val - $totaltobefunded) > $max_change)) {
$crt_iter++;
$prev_target_val = $totaltobefunded;
$totaltobefunded = ($discounted_otr - $first_reg_fee - 0 /* Emissions */) / $vat - $deposit;
$vatbal = $discounted_otr - $first_reg_fee - 0 /* Emissions */ - $totaltobefunded;
if($vehicletype == "Car") {
$balloon = $price / $vat * 0.9;
} else {
$balloon = $price * 0.9;
}
$totalamountborrowed = $totaltobefunded - $balloon;
$fundingrental = $totalamountborrowed * $lom_a / 1000;
$balloonrental = $balloon * $lom_b / 1000;
$monthlyfinancerental = $fundingrental + $balloonrental;
$monthlyrentalwithfees = $monthlyfinancerental + $fees;
$totalmargin = $margin * $contract_term;
$totalrentalandfees = $monthlyrentalwithfees * ($contract_term + $deposit_months -1);
$totalcontractcost = $totalmargin + $totalrentalandfees;
$actualmonthlyrental = $totalcontractcost / ($contract_term + $deposit_months -1);
$deposit = $actualmonthlyrental * $deposit_months;
}
print '<p>Final Number: <strong>' . $actualmonthlyrental . '</strong></p>';
?>

get rid of "dividing by zero" warning in sessions

This is a game of guessing number, I want the page to keep track of the wins, losses and totals and the %of winning by using sessions. I want to reset everything when I click "reset", but when I click reset everything equals to zero and there will be a warning saying "dividing by zero". How do I rearrange this php for it to only do the %calculation when the game is played but not when it's being reset?
<?php
// initialize wins and losses
if ($_SESSION['wins'] == "") {
$_SESSION['wins'] = 0;
}
if ($_SESSION['losses'] == "") {
$_SESSION['losses'] = 0;
}
echo "<h1>PHP SESSIONS</h1>";
if ($_GET['reset'] == "yes") {
$_SESSION['wins'] = 0;
$_SESSION['losses'] = 0;
$_SESSION['total'] = 0;
echo "<p>The game has been reset.</p>";
} else {
$randNum = rand(1,5);
echo "<p>The random number is <b>" . $randNum . "</b></p>";
if ($randNum == 3) {
echo "<p>The number equalled 3. YOU WIN!</p>";
$_SESSION['wins'] = $_SESSION['wins'] + 1;
} else {
echo "<p>The number did NOT equal 3. YOU LOSE!</p>";
$_SESSION['losses'] = $_SESSION['losses'] + 1;
}
$_SESSION['total'] = $_SESSION['total'] + 1;
}
$_SESSION ['percentage'] = (($_SESSION['wins']) / ($_SESSION['total'])) * 100 ;
echo "<p>WINS: " . $_SESSION['wins'] . " | LOSSES: " . $_SESSION['losses'] . "| TOTAL: " . $_SESSION['total'] . "</p>";
echo "<p>Percentage of Winning: ". $_SESSION ['percentage'] . " % </p>"
?>
ROLL AGAIN :)
RESET :)
Move up the line in which you are dividing:
$_SESSION ['percentage'] = (($_SESSION['wins']) / ($_SESSION['total'])) * 100 ;
Put it inside the else bracket. Once I reformatted your code, it was easy to see the problem. I'd advise always using proper indenting. :)
When $_GET['reset'] == 'yes' is satisfied, you are setting $_SESSION['total'] = 0.
Then, you're dividing $_SESSION['wins'] by a 0 valued $_SESSION['total'] in the following line (which is executed regardless of the current state of $_SESSION['total']:
$_SESSION ['percentage'] = (($_SESSION['wins']) / ($_SESSION['total'])) * 100 ;
It's easier to see what's going on when the code is properly formatted. Have a look:
if ($_GET['reset'] == "yes") { // reset called
$_SESSION['wins'] = 0;
$_SESSION['losses'] = 0;
$_SESSION['total'] = 0; // set to zero(0)
echo "<p>The game has been reset.</p>";
} else {
$randNum = rand(1,5);
echo "<p>The random number is <b>" . $randNum . "</b></p>";
if ($randNum == 3) {
echo "<p>The number equalled 3. YOU WIN!</p>";
$_SESSION['wins'] = $_SESSION['wins'] + 1;
} else {
echo "<p>The number did NOT equal 3. YOU LOSE!</p>";
$_SESSION['losses'] = $_SESSION['losses'] + 1;
}
$_SESSION['total'] = $_SESSION['total'] + 1;
}
$_SESSION ['percentage'] = (($_SESSION['wins']) / ($_SESSION['total'])) * 100; // chance that $_SESSION['total'] is zero(0)
So again, when you call the reset action, $_SESSION['total'] is given a value of int(0). Later in the script you then divide by that int(0), giving you the error in question. Make sense?
So you first need to ensure $_SESSION['total'] is greater than 0 before dividing by it.

Pay Rate Calculator

I've looked online but all the $_POST and $_GET examples are for text not numbers.
This is not connecting to a database. It doesn't need form validation. It's just a single page project running locally on my system. I want to keep it as simple as possible.
The goal is to have an input where you can put in your hourly pay. For example 15.
Then when you press submit it posts back to the same page with a nice list of how much you make daily, weekly, monthly, and yearly.
Any help would be greatly appreciated.
<p>Input your Hourly Pay</p>
<form method="GET" action="" >
<input name="num1" type="text" >
<input type="submit" name="submit" value="Submit">
</form>
<?php
if ($_GET['num1']) {
$rate = $_GET['num1'];
return $rate;
}
$result_day= $rate * 8;
$result_week = $rate * 8 * 5;
$result_month = $rate * 8 * 5 * 4;
$result_year = $rate * 8 * 5 * 4 * 12;
echo "Rate: " . $rate . "<br>";
echo "Daily: " . $result_day . "<br>";
echo "Weekly: " . $result_week . "<br>";
echo "Monthly: " . $result_month . "<br>";
echo "Yearly: " . $result_year . "<br>";
?>
I did some correction, but the calculation is still your original:
<?php
if (isset($_GET['num1'])) {
$rate = $_GET['num1'];
$result_day= $rate * 8;
$result_week = $result_day * 5;
$result_month = $result_week * 4;
$result_year = $result_month * 12;
echo "Rate: " . $rate . "<br>";
echo "Daily: " . $result_day . "<br>";
echo "Weekly: " . $result_week . "<br>";
echo "Monthly: " . $result_month . "<br>";
echo "Yearly: " . $result_year . "<br>";
}else{
echo "Please enter your rate!";
}
Use the onchange event with Javascript on any of the fields. You can then use Javascript to calculate the rest of the values and update those fields.
No PHP required. No time lag with a new page required. Users will love it.

Categories