πΈ Build a Tip Calculator
Bill amount + tip percent β tip and total. Practices: variables, operators, functions, I/O.
What You'll Build
A function that takes a bill amount and a tip percentage and returns the tip and the total. Then we wrap it in an interactive prompt.
Step 1 β the Core Function
function calcTip(bill, percent) {
const tip = bill * (percent / 100);
const total = bill + tip;
return { tip, total };
}
console.log(calcTip(50, 18));
// { tip: 9, total: 59 }def calc_tip(bill, percent):
tip = bill * (percent / 100)
total = bill + tip
return { "tip": tip, "total": total }
print(calc_tip(50, 18))Step 2 β Round Nicely
Currency should usually be 2 decimal places.
javascript
function calcTip(bill, percent) {
const tip = +(bill * percent / 100).toFixed(2);
const total = +(bill + tip).toFixed(2);
return { tip, total };
}Step 3 β Split the Bill
javascript
function splitBill(bill, percent, people) {
const { total } = calcTip(bill, percent);
return +(total / people).toFixed(2);
}
splitBill(50, 18, 4); // 14.75Stretch Goals
- Add a button on a webpage that runs the calculator on form input.
- Validate input β reject negative bills, zero people.
- Round up the per-person amount so the actual tip is at least the requested %.