To implement a bill splitting function in JavaScript, you can use the following code:
function billSplitter(total, numPeople) {
const amountPerPerson = total / numPeople;
console.log(`Each person should pay $${amountPerPerson.toFixed(2)}.`);
}
const totalBill = prompt("Enter the total bill:");
const numPeople = prompt("Enter the number of people:");
billSplitter(totalBill, numPeople);
This code prompts the user to enter the total bill and the number of people, then calls the billSplitter function with the entered values. The function calculates the amount each person should pay by dividing the total bill by the number of people, and logs the result to the console, rounded to the nearest cent.
Note that the prompt function in JavaScript returns a string, so you will need to convert the entered values to numbers using the parseFloat function for the total bill (since it is a decimal number) and the parseInt function for the number of people (since it is an integer).
Here is the modified code that takes this into account:
function billSplitter(total, numPeople) {
const amountPerPerson = total / numPeople;
console.log(`Each person should pay $${amountPerPerson.toFixed(2)}.`);
}
const totalBill = parseFloat(prompt("Enter the total bill:"));
const numPeople = parseInt(prompt("Enter the number of people:"));
billSplitter(totalBill, numPeople);
This code prompts the user to enter the total bill and the number of people, then calls the bill_splitter function with the entered values. The function calculates the amount each person should pay by dividing the total bill by the number of people, rounds the result to the nearest cent, and prints it.
Top comments (0)