Hi All, I need some help with some PHP coding work, assist would be greatly appr
ID: 3708169 • Letter: H
Question
Hi All,
I need some help with some PHP coding work, assist would be greatly appreciated.
Create a web application that calculates the correct amount of change to return when performing a cash transaction. Allow the user (a cashier) to enter the cost of a transaction and the exact amount of money that the customer hands over to pay for the transaction.
Then determine the largest amount of each denomination to return to the customer. Assume that the largest denomination a customer will use is a $100 bill. Therefore, you need to calculate the correct amount of change to return, the number of $50, $20, $10, $5, and $1 bills to return, and the number of quarters, dimes, nickels, and pennies to return. For example, if the price of a transaction is $5.65 and the customer hands the cashier $10, the cashier should return $4.35 to the customer as four $1 bills, a quarter, and a dime.
Use a Smarty template design that effectively separates the business logic required to perform calculations from web presentations used to accept user inputs and display results.
Explanation / Answer
<?php
function change($tender, $price)
{
/**
* function to calculate change
* Returns array of currency denominations and how many of each
*/
$demom = array(5000, 2000, 1000, 500, 100, 25, 10, 5, 1);
$change = ($tender - $price)*100;
$result = array();
foreach ($demom as $v)
{
if ($change > $v)
{
$x = floor($change/$v);
$result[$v] = $x;
$change -= $v*$x;
}
}
return $result;
}
/**
* get form data and process
*/
if (isset($_POST['B1']))
{
$tender = $_POST['tender'];
$price = $_POST['price'];
/**
* pass values to function
*/
$res = change($tender, $price);
/**
* print results of the function
*/
echo '<table align="center" width="200" border="1">';
echo '<tr><th colspan="2">Change</th></tr>';
printf ('<tr><th colspan="2">$%0.2f</th></tr>',$tender-$price);
foreach ($res as $d => $n)
{
printf ('<tr><td>$%0.2f</td><td>%d</td></tr>', $d/100, $n);
}
echo '</table><hr>';
}
?>
<html>
<head>
<title>Values</title>
</head>
<body bgcolor="#000000" text="#FFFFFF">
<form action="", METHOD=POST>
<p align="center">
Please enter the total amount and total cash then press Submit.
<p align="center">
<form>
<p align="center">Total Price:
<input type="text" name="price" size="5" maxlength="5">
Total cash tendered:
<input type="text" name="tender" size="5" maxlength="5">
<p align="center">
<input type="submit" value="Submit" name="B1">
<input type="reset" value="Reset" name="B2">
</p>
</form>
</body>
</html>