I'm trying to learn Javascript and I've set up a bill calculator. Most of the lines in the code are to deal with rounding. It has four main components:
- Allows you to enter the bill amount and tip percentage.
- Calculates the total bill divided by the number of guests.
- Calculates the total tip.
- Splits the bill by the number of guests.
billAmount = 134.93
const enterTipPercent = 10
const guests = ["Person1", "Person2", "Person3", "Person4"]
const noOfGuests = guests.length;
console.log('Chosen tip: ' + enterTipPercent + '%')
function splitBill() {
var split = billAmount / noOfGuests;
var rounding = split.toFixed(2);
var elseIf = rounding * noOfGuests;
if (rounding == billAmount/noOfGuests) {
console.log('Each person must pay: £' + rounding +' with no remainder');
}
else if (elseIf * noOfGuests > billAmount){
var roundDown = Math.floor(split*100) /100;
var remainingAmount = billAmount-roundDown*noOfGuests;
var roundedRemainder = remainingAmount.toFixed(2);
console.log('Each person must pay: £' + roundDown +' with £' + roundedRemainder + ' remaining');
}
}
function calculateTip() {
var tip = billAmount/100*enterTipPercent;
var tipRound = tip.toFixed(2);
return tipRound;
}
function splitTip() {
if (calculateTip() * 10 == billAmount) {
var tipShare = calculateTip();
var tipDivide = tipShare/noOfGuests;
var tipRound = tipDivide.toFixed(2);
console.log('Each person must tip: £' + tipRound);
}
else {
var tipShare = calculateTip();
var tipDivide = tipShare/noOfGuests;
var tipRound = Math.floor(tipDivide *100) /100;
var tipremainder = calculateTip()-tipRound*noOfGuests;
var tipRoundRemainder = tipremainder.toFixed(2);
console.log('Each person must tip: £' + tipRound + ' with £' + tipRoundRemainder + ' remaining');
}
}
splitBill();
console.log('total tip £' + calculateTip());
splitTip();const
The code I've written works fine, but I'm sure this isn't the best, or most efficient way I could have done it. Does anyone have any advice on how I can improve?