Part 01 · Rust Is Not Scary

Build: A Bill Splitter CLI

InputParsingFunctionsLoops

A small command line tool that splits a restaurant bill between friends, with tip and rounding. Your first real Rust program.

⏱ 1-2 hours · Station 10 of 75

Goal

Three friends finish dinner at a restaurant in Dhanmondi. The bill is ৳1250.50, they want to leave a 10% tip, and somebody opens a calculator app. "416.83 each... wait, with the tip... who pays the extra paisa?" Five minutes of arguing over two paisa.

You'll build a small command line tool that settles it:

bill-splitter 1250.50 3 10
bill       1250.50
tip 10%     125.05
total      1375.55
--------------------
person 1     458.52
person 2     458.52
person 3     458.51

It takes the bill, the number of people, and an optional tip percent. It adds the tip rounded to the nearest paisa, and splits the total so the shares add up exactly: everyone pays the same, and the leftover paisa go to the first few people. It rejects bad input with a clear message instead of crashing, and it comes with tests.

It is your first real Rust program, and it uses everything from Part 1: cargo, variables and mut, number types, functions, if, loops, Option, and reading compiler messages.

Prerequisites

A few things in this project are only introduced here and taught properly later. You'll see a short note each time; using them now is fine, you don't need the full story yet:

Architecture

The program is a straight line: text comes in, becomes whole paisa, gets a tip, is split, and is printed back as taka.

args"1250.50" "3" "10"parse_takatext to paisatip10%, roundedsplitequal + leftoverprinttaka(...)"1250.50"1250501375553 sharesbill 125050 + tip 12505 = 137555 paisa137555 / 3 = 45851, leftover 2: two people pay 1 paisa more458.52 + 458.52 + 458.51 = 1375.55, not a paisa losttext in, paisa inside, exact shares out
The bill splitter's flow: the command line arguments are text, parse_taka turns "1250.50" into 125050 paisa, tip adds 12505, split divides 137555 into three shares that add up exactly, and print shows them as taka.

Four small functions, each with one job, plus main to connect them:

FunctionInputOutputJob
parse_taka"1250.50"Some(125050) or Noneturn text into paisa, reject anything that isn't money
tip125050, 1012505percent of the bill, rounded to the nearest paisa
split137555, 3[45852, 45852, 45851]equal shares that add up exactly
taka45852"458.52"paisa back to text for printing

Everything inside is a u64 in paisa. Text only exists at the edges: when it comes in, and when it goes out. That one decision removes all the 0.1 + 0.2 problems from basic types.

Steps

Eight small steps. Steps 2 to 4 each write one function from the table above, and steps 5 to 7 build main in three parts. The whole main is at the end of this section if you want to copy it in one go.

Step 1: create the project and read the command line

cargo new bill-splitter
cd bill-splitter

Your program gets what the user typed after its name through std::env::args(). Try it with a throwaway program first. Anything after -- in cargo run is passed to your program, not to cargo:

use std::env;

fn main() {
    let args: Vec<String> = env::args().collect();
    println!("{} arguments", args.len());
    for arg in args {
        println!("  {arg}");
    }
}
cargo run -- 1250.50 3 10
4 arguments
  target/debug/argsdemo
  1250.50
  3
  10

Two things to notice. The first argument is always the program's own path, so the user's values start at index 1. And every argument is text, even 3. Turning text into numbers safely is most of this project.

Step 2: parse taka into paisa

A bill can be typed as 1250.50, 1250.5 or 1250. Anything else (abc, 12.345, -5) is not a valid amount, so the function returns Option<u64>: Some(paisa) or None, like discount in Why Rust Feels Hard.

/// Turns text like "1250.50", "1250.5" or "1250" into paisa (125050).
/// Gives back None if the text is not a valid amount.
fn parse_taka(text: &str) -> Option<u64> {
    let (taka_part, paisa_part) = match text.split_once('.') {
        Some((t, p)) => (t, p),
        None => (text, ""),
    };
    let taka: u64 = match taka_part.parse() {
        Ok(n) => n,
        Err(_) => return None,
    };
    let paisa: u64 = match paisa_part.len() {
        0 => 0,
        1 => match paisa_part.parse::<u64>() {
            Ok(n) => n * 10, // "1250.5" means 50 paisa
            Err(_) => return None,
        },
        2 => match paisa_part.parse::<u64>() {
            Ok(n) => n,
            Err(_) => return None,
        },
        _ => return None, // more than 2 decimals: not money
    };
    // taka * 100 + paisa, without overflowing on a silly huge amount
    match taka.checked_mul(100) {
        Some(p) => p.checked_add(paisa),
        None => None,
    }
}

How it works:

  • split_once('.') cuts the text at the first dot. It returns Some((before, after)) if there is a dot, and None if there isn't. The (t, p) pair is a tuple, two values travelling together.
  • taka_part.parse() tries to read a u64. It answers Ok(n) or Err(...), and we turn Err into return None. Since a u64 can't be negative, -5 fails here, which is exactly what we want.
  • The paisa part is checked by length: no digits means 0, one digit means tens (.5 is 50 paisa), two digits are taken as they are, and three or more is not money.
  • checked_mul and checked_add from basic types make sure a ridiculous amount gives None instead of overflowing.

Step 3: add the tip, rounded properly

10% of 125050 paisa is 12505 exactly, but 10% of 1005 paisa is 100.5 paisa. Plain integer division would always round down. Adding half the divisor first rounds to the nearest paisa:

/// The tip on a bill, rounded to the nearest paisa (half a paisa rounds up).
fn tip(bill: u64, percent: u64) -> u64 {
    (bill * percent + 50) / 100
}
  • (1005 * 10 + 50) / 100 is 10100 / 100, which is 101. Without the + 50 it would be 100.
  • The idea works for any integer division: to round to the nearest, add half of what you divide by before dividing.

Step 4: split so it adds up exactly

The Functions practice found the problem: ৳1250.50 between three people is 416.83 each, with 1 paisa nobody pays. The fix: everyone pays the base share, and the leftover paisa are handed out one each to the first people:

/// Splits `total` between `people` so the shares add up exactly:
/// everyone pays the same, and the leftover paisa go to the first few people.
fn split(total: u64, people: u64) -> Vec<u64> {
    let base = total / people;
    let extra = total % people;
    let mut shares = Vec::new();
    for i in 0..people {
        let share = if i < extra { base + 1 } else { base };
        shares.push(share);
    }
    shares
}
  • base is the share everyone pays, and extra is the remainder. The remainder is always smaller than people, so nobody pays more than one extra paisa.
  • Vec::new() makes an empty list and push adds to the end (that's why shares needs mut).
  • The function returns the list as its last expression, with no semicolon.

Step 5: main, part 1: check the number of arguments

main checks the number of arguments, parses each one, and only then calculates. First the count: the program's own path plus two or three values, so 3 or 4 arguments in total.

fn main() {
    let args: Vec<String> = env::args().collect();
    if args.len() < 3 || args.len() > 4 {
        eprintln!("usage: bill-splitter <bill in taka> <people> [tip %]");
        eprintln!("example: bill-splitter 1250.50 3 10");
        process::exit(1);
    }
  • eprintln! prints to the error output, not normal output, so error messages don't get mixed into results if someone saves the output to a file.
  • process::exit(1) stops the program with exit code 1. By convention 0 means success and anything else means failure, which scripts and CI tools check.

Step 6: main, part 2: parse each argument, with a guard

main continues. Each value is turned from text into a number, and a bad one stops the program with a sentence that says what was wrong. The bill uses parse_taka from step 2, people and tip use parse().

    let bill = match parse_taka(&args[1]) {
        Some(paisa) => paisa,
        None => {
            eprintln!("error: '{}' is not an amount like 1250.50", args[1]);
            process::exit(1);
        }
    };
    let people: u64 = match args[2].parse() {
        Ok(n) if n > 0 => n,
        _ => {
            eprintln!("error: people must be a whole number above 0, got '{}'", args[2]);
            process::exit(1);
        }
    };
    let percent: u64 = if args.len() == 4 {
        match args[3].parse() {
            Ok(n) if n <= 100 => n,
            _ => {
                eprintln!("error: tip must be a whole percent from 0 to 100, got '{}'", args[3]);
                process::exit(1);
            }
        }
    } else {
        0
    };
  • Ok(n) if n > 0 => n is a match arm with a guard: it only matches when the condition is true. Zero people falls through to _, the error branch.
  • The tip is optional: with only 3 arguments, percent is 0. A tip above 100 is refused the same way as zero people.
  • Every error message repeats what the user typed (got '0'), so they can see their mistake at once.

Step 7: main, part 3: calculate and print

The end of main. By now every value is a valid number in paisa, so the calculation itself is four lines and cannot fail.

    let tip = tip(bill, percent);
    let total = bill + tip;
    println!("bill    {:>10}", taka(bill));
    println!("tip {percent:>2}% {:>10}", taka(tip));
    println!("total   {:>10}", taka(total));
    println!("--------------------");
    let mut person = 1;
    for share in split(total, people) {
        println!("person {person} {:>10}", taka(share));
        person += 1;
    }
}
  • let tip = tip(bill, percent); shadows the function name with a variable inside main. It's legal, but not great style; it's kept here to show that shadowing works on any name.
  • {:>10} right-aligns the text in 10 columns, which is why the amounts line up in the output.
  • taka is the only place paisa become text again: text exists only at the edges.

Checkpoint: bad input gets a sentence, not a panic

Why insist on n > 0 for people? Here's the same program with the guard removed, run with 0 people:

bill       1250.50
tip  0%       0.00
total      1250.50
--------------------

thread 'main' (1708636) panicked at src/main.rs:42:16:
attempt to divide by zero
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Division by zero is a panic in Rust, in every build mode. It's better than a wrong answer, but a user should never see a panic for a typo. With the guard, they get a sentence instead:

$ bill-splitter 12.345 3
error: '12.345' is not an amount like 1250.50
(exit code 1)
$ bill-splitter 1250.50 0
error: people must be a whole number above 0, got '0'
(exit code 1)
$ bill-splitter 1250.50 3 150
error: tip must be a whole percent from 0 to 100, got '150'
(exit code 1)
$ bill-splitter
usage: bill-splitter <bill in taka> <people> [tip %]
example: bill-splitter 1250.50 3 10
(exit code 1)

Step 8: try it

Without a tip:

cargo run -- 1250.50 3
bill       1250.50
tip  0%       0.00
total      1250.50
--------------------
person 1     416.84
person 2     416.83
person 3     416.83

Compare with the Functions practice, where three people paying 416.83 left the shop a paisa short. Now person 1 pays 416.84 and the shares add up to 1250.50 exactly.

When you're happy, build the release version. That single file is the whole tool; copy it anywhere on your PATH:

cargo build --release
    Finished `release` profile [optimized] target(s) in 0.01s
461K target/release/bill-splitter
bill        840.00
tip  5%      42.00
total       882.00
--------------------
person 1     220.50
person 2     220.50
person 3     220.50
person 4     220.50
Full code: fn main (steps 5 to 7 together)
fn main() {
    let args: Vec<String> = env::args().collect();
    if args.len() < 3 || args.len() > 4 {
        eprintln!("usage: bill-splitter <bill in taka> <people> [tip %]");
        eprintln!("example: bill-splitter 1250.50 3 10");
        process::exit(1);
    }

    let bill = match parse_taka(&args[1]) {
        Some(paisa) => paisa,
        None => {
            eprintln!("error: '{}' is not an amount like 1250.50", args[1]);
            process::exit(1);
        }
    };
    let people: u64 = match args[2].parse() {
        Ok(n) if n > 0 => n,
        _ => {
            eprintln!("error: people must be a whole number above 0, got '{}'", args[2]);
            process::exit(1);
        }
    };
    let percent: u64 = if args.len() == 4 {
        match args[3].parse() {
            Ok(n) if n <= 100 => n,
            _ => {
                eprintln!("error: tip must be a whole percent from 0 to 100, got '{}'", args[3]);
                process::exit(1);
            }
        }
    } else {
        0
    };

    let tip = tip(bill, percent);
    let total = bill + tip;
    println!("bill    {:>10}", taka(bill));
    println!("tip {percent:>2}% {:>10}", taka(tip));
    println!("total   {:>10}", taka(total));
    println!("--------------------");
    let mut person = 1;
    for share in split(total, people) {
        println!("person {person} {:>10}", taka(share));
        person += 1;
    }
}

Testing

Trying a few inputs by hand is good; tests are better, because they run every time you change something. Rust has testing built in. A function marked #[test] is a test, and assert_eq!(a, b) fails the test if a isn't equal to b. Put them at the bottom of main.rs:

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_amounts() {
        assert_eq!(parse_taka("1250.50"), Some(125050));
        assert_eq!(parse_taka("1250.5"), Some(125050));
        assert_eq!(parse_taka("1250"), Some(125000));
        assert_eq!(parse_taka("0.05"), Some(5));
    }

    #[test]
    fn rejects_bad_amounts() {
        assert_eq!(parse_taka("abc"), None);
        assert_eq!(parse_taka("12.345"), None);
        assert_eq!(parse_taka("-5"), None);
        assert_eq!(parse_taka(""), None);
    }

    #[test]
    fn tip_rounds_to_nearest_paisa() {
        assert_eq!(tip(125050, 10), 12505);
        assert_eq!(tip(1005, 10), 101); // 100.5 paisa rounds up
        assert_eq!(tip(125050, 0), 0);
    }

    #[test]
    fn shares_add_up_exactly() {
        for total in [100, 137555, 1, 999_999] {
            for people in 1..=7 {
                let shares = split(total, people);
                assert_eq!(shares.len() as u64, people);
                assert_eq!(shares.iter().sum::<u64>(), total);
                let (min, max) = (shares.iter().min().unwrap(), shares.iter().max().unwrap());
                assert!(max - min <= 1, "shares differ by at most one paisa");
            }
        }
    }
}
  • #[cfg(test)] means "only compile this module when testing", so the tests are not in your real program.
  • use super::*; lets the tests use the functions above them.
  • The last test doesn't check one example. It checks a rule for 28 combinations: there's the right number of shares, they add up to the total, and no two shares differ by more than one paisa. A rule-based test like this catches mistakes a single example would miss.
cargo test

running 4 tests
test tests::parses_amounts ... ok
test tests::rejects_bad_amounts ... ok
test tests::tip_rounds_to_nearest_paisa ... ok
test tests::shares_add_up_exactly ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

Finally, ask the second teacher from The Compiler Is Your Teacher:

cargo clippy
warning: the variable `person` is used as a loop counter
  --> src/main.rs:97:5
   |
97 |     for share in split(total, people) {
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `for (person, share) in (1..).zip(split(total, people).into_iter())`
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.98.0/index.html#explicit_counter_loop
   = note: `#[warn(clippy::explicit_counter_loop)]` on by default

warning: `bill-splitter` (bin "bill-splitter") generated 1 warning

Clippy noticed that person is a hand-made loop counter and suggests a shorter way with zip. It's a style warning, not a bug; you'll understand that suggestion fully in Iterators, and it's fine to leave it for now.

Trade-offs

  • Paisa in u64, not taka in f64. Exact arithmetic, and shares that always add up. The cost: parsing and printing need a bit of work (parse_taka, taka), which is why they're the biggest functions.
  • Who pays the extra paisa? We give it to the first people, which is simple and predictable. A restaurant app might give it to whoever paid the bill, or round everyone up and keep the change. The function makes the choice in one place, so it's easy to change.
  • Rounding the tip half up. Common and easy to explain. Banks often use "round half to even" to avoid a tiny upward bias over millions of transactions; for a dinner bill it doesn't matter.
  • Hand-written argument parsing. Fine for three arguments. Past that, a library like clap gives you --help, flags and good error messages for free; that's Command Line Apps with clap in Part 6.
  • process::exit in main. Simple and honest for a small tool. In a bigger program you'd return errors to main and handle them in one place, using Result and ? from Part 4.

Extend it

Try these in order. Each one practises something from Part 1:

  1. Show the per-person tip. Print how much of each share was tip. (Functions, integer maths.)

  2. Round shares to whole taka. Some people don't want paisa at all. Add a flag so everyone pays a whole number of taka, and print how much extra the group pays in total. (if, %.)

  3. Reject a leading +. parse accepts +5 as 5, so this input slips through as 12.05 taka:

    bill         12.05
    tip  0%       0.00
    total        12.05
    --------------------
    person 1       6.03
    person 2       6.02

    Add a check that every character of the amount is a digit (or the one dot). Write a test for it first and watch it fail, then fix it.

  4. Uneven split. Let the user give weights, like 2 1 1 when one friend ate twice as much, and split in proportion while still adding up exactly. (Loops, Vec, the same leftover trick.)

When you can do 3 without looking anything up, you're ready for Part 2: ownership, the idea that makes Rust Rust.

Station stamp

Finish the chapter

Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +25 XP.

Go Pro to earn XP →