Skip to content
Java project #04Beginner

Restaurant Bill Splitter

Split shared restaurant items between friends with tax and tip, using BigDecimal so the shares are exact and always add up to the total.

Estimated time
~3 hours to build
Files
4 files · 298 lines
Technologies
Java 21, java.math.BigDecimal, RoundingMode, LinkedHashMap

Introduction

Splitting a bill sounds trivial until three people share an item and the paise don't divide evenly. This project uses BigDecimal for exact decimal arithmetic and the largest-remainder method to distribute leftover paise fairly, so the shares always add up to the bill.

Problem statement

Let users add people, add items with a price and the people who shared them (or all), set tax and tip percentages and request a split at any time. Reject duplicate people, unknown names, invalid prices (non-positive or more than two decimals) and percentages outside 0–100. The split shows the subtotal, tax, tip and total, and each person's share, rounded to paise so that the shares sum exactly to the total.

Objectives

  • Use BigDecimal for money and understand scale and rounding modes
  • Keep ordered per-person data in a LinkedHashMap
  • Implement fair rounding with the largest-remainder method
  • Build a small command interpreter

Features

  • Items shared by any subset of people, or all
  • Tax and tip, including fractional percentages
  • Exact shares that always sum to the total
  • Clear error messages for every invalid command

Concepts demonstrated

  • Exact decimal arithmetic
  • Rounding modes
  • Largest-remainder apportionment
  • Maps
  • Command parsing

System architecture

Commands are parsed in a switch. Items are stored as records of a price and a list of names. split first divides each item's price exactly (10 decimal places) among its sharers and multiplies each person's total by (1 + tax + tip). It then rounds every share *down* to paise, computes how many paise are left over compared with the properly rounded total, and gives one paisa each to the people whose rounding lost the most. Finally it verifies that the shares add up to the total.

Folder structure

TextProject tree
bill-splitter/
├── README.md
├── src/Main.java
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

src/Main.java

123 lines
Javasrc/Main.java
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
/**
* Bill Splitter — enter shared items and who had them, add tax and a tip, and get an exact
* per-person split using BigDecimal. Leftover paise from rounding are distributed fairly so
* the shares always add up to the bill total.
*
* Commands: person NAME | item PRICE NAME... | tax PERCENT | tip PERCENT | split | quit
*/
public class Main {
record Item(BigDecimal price, List<String> people) { }
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Map<String, BigDecimal> subtotals = new LinkedHashMap<>(); // keeps the order people were added
List<Item> items = new ArrayList<>();
BigDecimal taxPct = BigDecimal.ZERO, tipPct = BigDecimal.ZERO;
System.out.println("=== Bill Splitter ===");
while (true) {
System.out.print("> ");
if (!in.hasNextLine()) break;
String[] p = in.nextLine().trim().split("\\s+");
System.out.println();
String cmd = p[0].toLowerCase();
try {
switch (cmd) {
case "person" -> {
if (p.length != 2) throw new IllegalArgumentException("usage: person NAME");
if (subtotals.putIfAbsent(p[1], BigDecimal.ZERO) != null) throw new IllegalArgumentException(p[1] + " is already on the bill");
System.out.println("Added " + p[1]);
}
case "item" -> {
if (p.length < 3) throw new IllegalArgumentException("usage: item PRICE NAME [NAME...] (or 'all')");
BigDecimal price = money(p[1]);
List<String> who = new ArrayList<>();
for (int i = 2; i < p.length; i++) {
if (p[i].equalsIgnoreCase("all")) who.addAll(subtotals.keySet());
else if (!subtotals.containsKey(p[i])) throw new IllegalArgumentException("unknown person " + p[i]);
else who.add(p[i]);
}
if (who.isEmpty()) throw new IllegalArgumentException("add people first");
items.add(new Item(price, who));
System.out.println("Item Rs " + price + " shared by " + String.join(", ", who));
}
case "tax", "tip" -> {
if (p.length != 2) throw new IllegalArgumentException("usage: " + cmd + " PERCENT");
BigDecimal pct = new BigDecimal(p[1]);
if (pct.signum() < 0 || pct.compareTo(BigDecimal.valueOf(100)) > 0) throw new IllegalArgumentException("percent must be 0-100");
if (cmd.equals("tax")) taxPct = pct; else tipPct = pct;
System.out.println(cmd + " set to " + pct + "%");
}
case "split" -> split(subtotals, items, taxPct, tipPct);
case "quit" -> { return; }
default -> System.out.println("Commands: person, item, tax, tip, split, quit");
}
} catch (NumberFormatException e) {
System.out.println("Error: not a number");
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
static BigDecimal money(String text) {
BigDecimal v = new BigDecimal(text);
if (v.signum() <= 0 || v.scale() > 2) throw new IllegalArgumentException("price must be positive with at most 2 decimals");
return v.setScale(2);
}
static void split(Map<String, BigDecimal> people, List<Item> items, BigDecimal taxPct, BigDecimal tipPct) {
if (items.isEmpty()) {
System.out.println("No items yet.");
return;
}
// 1. Share each item's price exactly (in fractions of a paisa) between the people who had it.
Map<String, BigDecimal> exact = new LinkedHashMap<>();
people.keySet().forEach(n -> exact.put(n, BigDecimal.ZERO));
BigDecimal subtotal = BigDecimal.ZERO;
for (Item item : items) {
subtotal = subtotal.add(item.price());
BigDecimal share = item.price().divide(BigDecimal.valueOf(item.people().size()), 10, RoundingMode.HALF_EVEN);
for (String n : item.people()) exact.merge(n, share, BigDecimal::add);
}
BigDecimal factor = BigDecimal.ONE.add(taxPct.add(tipPct).movePointLeft(2));
BigDecimal tax = subtotal.multiply(taxPct).movePointLeft(2).setScale(2, RoundingMode.HALF_UP);
BigDecimal tip = subtotal.multiply(tipPct).movePointLeft(2).setScale(2, RoundingMode.HALF_UP);
BigDecimal total = subtotal.add(tax).add(tip);
// 2. Round everyone down to whole paise, then hand out the leftover paise one at a time
// to the people whose rounding cut the most (largest-remainder method).
Map<String, BigDecimal> rounded = new LinkedHashMap<>();
BigDecimal sum = BigDecimal.ZERO;
for (var e : exact.entrySet()) {
BigDecimal r = e.getValue().multiply(factor).setScale(2, RoundingMode.DOWN);
rounded.put(e.getKey(), r);
sum = sum.add(r);
}
int leftoverPaise = total.subtract(sum).movePointRight(2).intValueExact();
List<String> order = new ArrayList<>(exact.keySet());
order.sort((a, b) -> exact.get(b).multiply(factor).subtract(rounded.get(b)).compareTo(exact.get(a).multiply(factor).subtract(rounded.get(a))));
for (int i = 0; i < leftoverPaise; i++) rounded.merge(order.get(i % order.size()), new BigDecimal("0.01"), BigDecimal::add);
System.out.printf("Subtotal Rs %10s%n", subtotal);
System.out.printf("Tax %4s%% Rs %10s%n", taxPct.stripTrailingZeros().toPlainString(), tax);
System.out.printf("Tip %4s%% Rs %10s%n", tipPct.stripTrailingZeros().toPlainString(), tip);
System.out.printf("Total Rs %10s%n", total);
System.out.println("Each person pays:");
BigDecimal check = BigDecimal.ZERO;
for (var e : rounded.entrySet()) {
System.out.printf(" %-8s Rs %8s%n", e.getKey(), e.getValue());
check = check.add(e.getValue());
}
System.out.println("Shares add up to the total: " + (check.compareTo(total) == 0));
}
}

What each file does

src/Main.java
The command loop, money validation, and split with exact sharing and fair rounding.

How to run it

Compile

Terminal
javac -d out $(find src -name "*.java")
# Windows PowerShell: javac -d out (Get-ChildItem -Recurse src -Filter *.java).FullName

Run

Terminal
java -cp out Main

Test against the expected output

Terminal
java -cp out Main < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | java -cp out Main > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
=== Bill Splitter ===
>
Added Asha
>
Added Ravi
>
Added Meera
>
Error: Ravi is already on the bill
>
Item Rs 450.00 shared by Asha, Ravi, Meera
>
Item Rs 320.50 shared by Asha, Ravi
>
Item Rs 180.00 shared by Meera
>
Error: price must be positive with at most 2 decimals
>
Error: unknown person John
>
tax set to 5%
>
tip set to 10%
>
Subtotal Rs 950.50
Tax 5% Rs 47.53
Tip 10% Rs 95.05
Total Rs 1093.08
Each person pays:
Asha Rs 356.79
Ravi Rs 356.79
Meera Rs 379.50
Shares add up to the total: true
>
Item Rs 100.00 shared by Asha, Ravi, Meera
>
tip set to 12.5%
>
Subtotal Rs 1050.50
Tax 5% Rs 52.53
Tip 12.5% Rs 131.31
Total Rs 1234.34
Each person pays:
Asha Rs 403.71
Ravi Rs 403.71
Meera Rs 426.92
Shares add up to the total: true
>
Input
person Asha
person Ravi
person Meera
person Ravi
item 450 all
item 320.50 Asha Ravi
item 180 Meera
item 99.999 Asha
item 60 John
tax 5
tip 10
split
item 100 all
tip 12.5
split
quit

Testing

  • Run with tests/sample-input.txt and compare with tests/expected-output.txt.
  • Asha and Ravi each owe (150 + 160.25) × 1.15 = 356.7875, so after rounding down one leftover paisa goes to each of them: 356.79.
  • A price of 99.999 and an unknown person are rejected.
  • Both splits end with 'Shares add up to the total: true'.

Common errors

ArithmeticException: Non-terminating decimal expansion

BigDecimal.divide needs a scale and rounding mode when the result doesn't terminate (e.g. dividing by 3).

Shares add up to 1 paisa less than the total

Rounding each share independently loses paise; distribute the difference as split does.

Possible improvements

  • Support discounts and service charges
  • Allow unequal shares (e.g. 2 parts for one person)
  • Print a settle-up plan: who pays whom

Additional challenges

  1. 1Add a 'remove item' command.
  2. 2Split by percentage instead of by item.
  3. 3Show each person's itemised share.

Built and tested it yourself? Mark it to update your dashboard.