Skip to content
Tutorials Center
My learning

Topics

Lesson 142 of 156 Β· Projects

Project: Loan, BMI, Tip, Age and Percentage Calculators

Build six form-driven calculators (loan, BMI, tip, age, percentage, aspect ratio) with a data-driven form builder, input validation and correct rounding.

Online calculators are some of the most visited pages on the web, and they are a perfect small project: a handful of inputs, a formula, a result. The interesting engineering is everything around the formula: parsing what people type, rejecting nonsense with a helpful message, rounding money correctly and handling dates.

You will build six calculators (loan payment, BMI, tip splitter, age, percentage and aspect ratio) as pure functions, then connect all of them to one small form builder, so adding a seventh takes ten lines. It builds on Form Handling, Numbers and Dates. For a four-function and scientific calculator with a safe expression parser, see Project: Calculator.

Step 1: The formulas as pure functions

Keep the math separate from the page. A pure function takes numbers and returns numbers, so you can test it in the console with no HTML. Three rules save you from the usual bugs:

  1. Validate before you compute. Throw an Error with a human message such as "Interest rate can't be negative"; the UI will show error.message.
  2. Money in cents. 0.1 + 0.2 is 0.30000000000000004. For tips and splits, round to whole cents with Math.round(value * 100) and divide by 100 only for display.
  3. Handle the zero case. A loan with a 0% rate would divide by zero in the standard formula, so it needs its own branch.

The monthly loan payment for principal P, monthly rate r and n payments is PΒ·r / (1 βˆ’ (1 + r)^βˆ’n).

JS Step 1: Loan, BMI, tip and percentage functions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Note the tip split: with a total of $101.95 for three people, one third is $33.9833..., so we round up to $33.99. In real life someone has to cover the last cent, and rounding up keeps the table from coming up short.

Step 2: Age from a birthdate, and aspect ratios

Two more calculators need a little more care.

Age is "full years, then months, then days since the last birthday". Subtracting years alone is wrong before the birthday, so subtract each part and borrow when one goes negative: a negative day count borrows the length of the previous month, a negative month count borrows 12 months. Do the arithmetic with UTC dates so that daylight saving time can never shift a day (see Dates).

Aspect ratio divides both sides by their greatest common divisor, so 1920 by 1080 becomes 16:9. To resize while keeping the ratio, scale the other side by the same factor.

JS Step 2: Age and aspect ratio

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The 2000-02-29 example (a leap-day birthday) shows why the borrowing approach is more reliable than dividing milliseconds by a year length: the answer is 22 years, 11 months and 30 days, exactly what a person would count.

Step 3: One form builder for every calculator

Each calculator needs the same things: labelled inputs, a Calculate action, an error message and a result list. Instead of writing six forms, describe each calculator as data:

JavaScript
{ name: "Tip", fields: [{ id: "bill", label: "Bill", value: 86.4, step: 0.01 }, ...], run: (v) => [["Tip", "$15.55"], ...] }

and write one function that turns the description into a form. The builder handles the shared rules: every field must contain a finite number, and any Error thrown by run() appears in an aria-live area so assistive technology announces it.

Step 3: Six calculators from one form builder

Try it: switch to Tip, type 0 in People and read the message; type abc in any field and watch the red border and the error. Choose Percent, enter 0 for B and notice that "what percent" simply does not appear instead of showing Infinity.

Points worth noticing:

  • inputmode="decimal" brings up a number keypad on phones, while type="text" avoids the quirks of type="number" (it silently returns an empty string for invalid text and hides what the person typed). We accept both 1,5 and 1.5 by replacing the comma.
  • Validation is two layers. The builder checks "is this a number?" for every calculator, and each run() checks the rules that belong to its own formula.
  • Results are built with textContent, so nothing a person types can become markup.
  • The form recalculates on every input event for instant feedback; errors in a half-typed value are expected, which is why they are shown inline and never with alert().

Ideas to extend it

  • Amortization table for the loan: for each month, interest = balance Γ— r, principal = payment βˆ’ interest.
  • Imperial units for BMI with a unit switch: 703 Γ— pounds / inchesΒ².
  • Currency by locale using Intl.NumberFormat(undefined, ...).
  • Shareable results: write the values into the URL's query string with URLSearchParams and read them on load.
  • Unit tests for the pure functions with the technique from Testing.

Check your understanding

Quick check Β· 4 questions

of 4 answered You scored / 4 Β· perfect!

  1. 1. Why do money calculations usually work in whole cents?

    Floating-point numbers use binary fractions, so many decimals are approximate. Rounding to integers of the smallest unit keeps totals exact.
  2. 2. Which part of the loan formula needs a special case when the interest rate is 0%?

    With r = 0, 1 - (1 + 0) ** -n is 0. The payment is simply amount / n.
  3. 3. When calculating age, what do you do when the day difference is negative?

    That is borrowing, exactly like in column subtraction. The borrowed amount is the number of days in the month before the current one.
  4. 4. Why does the form builder use type="text" with inputmode="decimal" instead of type="number"?

    A type="number" input hides what the person typed when it isn't a valid number. A text input keeps the raw text so you can parse it and explain the problem.

Summary

  • Write calculators as pure functions that validate, throw descriptive errors and return plain values.
  • Use whole cents for money, round deliberately and handle zero and negative inputs.
  • Age needs borrowing (days from the previous month, months from the year); use UTC dates and validate the format and the calendar date.
  • Reduce an aspect ratio with the greatest common divisor.
  • Describe calculators as data and build the form with one function; show errors in a live region and mark bad fields with aria-invalid.
  • Use inputmode="decimal" and parse the text yourself instead of trusting type="number".

Next: Project: QR Generator and Image Resizer.