In: Computer Science
Must use prompts to get input from user and alerts for output. Do not use jQuery or document.getElementById to solve these problems.
User input validation is not required. Assume the user will enter correct values and write your program. Program should run once and exit.
1. Filenames: tip.html & tip.js
Write a Tip program where the user enters a restaurant bill total.
The program should then display two amounts: a 15 percent tip and a
20 percent tip. The output should look similar to this:
Total bill: 44.9 15% tip = 6.735 and 20% tip = 8.98 |
2. Filenames: Tax.html & Tax.js
Write a check out program that calculates the total cost (total
price of items + 6% sales tax) of buying two items. Use floats for
this problem and format them to 2 decimal places before printing
them. The output should look similar to this:
Cost of Item1: 40.0 Total price of two items: 54.55 6% Sales tax = 3.27 Total cost = 57.82 |
Always format numbers after all calculations have been completed and your program is ready to display the result.
Formatting to a specific decimal place using the toFixed method:
var num = 2347.67890;
num = num.toFixed(2); -> This converts the num into a string
alert(num); -> 2347.67
alert(num.toFixed(2)) should be good for display purposes. There is no need to convert and update the variable num.
tip.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Tip</title>
<script type="text/javascript"
src="tip.js"></script>
<script>
var bill=window.prompt("Enter total bill");
var tip1=calculate15Tip(bill);
var tip2=calculate20Tip(bill);
var text="Total Bill:"+bill+"\n15% tip ="+tip1+" and 20% tip
="+tip2;
alert(text);
</script>
</head>
<body>
</body>
</html>
tip.js:
function calculate15Tip(bill){
var num=0.15*bill;
return num.toFixed(2);
}
function calculate20Tip(bill){
var num=0.20*bill;
return num.toFixed(2);
}
Expected output:
tax.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Tax</title>
<script type="text/javascript"
src="tax.js"></script>
<script>
var cost1=window.prompt("Enter cost of item 1:");
var cost2=window.prompt("Enter cost of item 2:");
var tax=calculateTax(cost1,cost2);
var totalprice=calculateTotalwoTax(cost1,cost2);
var finalprice=calculateTotalCost(cost1,cost2);
var text="Cost of item1: "+cost1+"\nCost of item2: "+cost2+"\nTotal
price of two items: "+totalprice+
"\n6% Sales tax = "+tax+"\nTotal
cost = "+finalprice;
alert(text);
</script>
</head>
<body>
</body>
</html>
tax.js:
function calculateTax(cost1,cost2){
var
tax=(parseFloat(cost1)+parseFloat(cost2))*0.06;
return tax.toFixed(2);
}
function calculateTotalwoTax(cost1,cost2){
var cost=parseFloat(cost1)+parseFloat(cost2);
return cost.toFixed(2);
}
function calculateTotalCost(cost1,cost2){
return (parseFloat(calculateTotalwoTax(cost1,
cost2))+parseFloat(calculateTax(cost1, cost2))).toFixed(2);
}
Expected output: