DEV Community

Adeyemi Raji
Adeyemi Raji

Posted on

3 1

How to implement bill splitting function using Javascript

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);

Enter fullscreen mode Exit fullscreen mode

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);

Enter fullscreen mode Exit fullscreen mode

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay