← Web basics: HTML, CSS and JavaScript

Project: a tip calculator

Read numbers from a form, calculate, and show money nicely.

Start this lesson

A tip calculator reads two numbers (the bill and the tip percent), does a little math and shows the result. Good structure: put the math in a plain function, like tipAmount(bill, percent), that knows nothing about the page. Then a click handler reads the inputs, converts them with Number(), calls the function and writes the answer with toFixed(2) so it looks like money. Finally, handle bad input kindly instead of showing NaN.

function tipAmount(bill, percent) {
  return bill * percent / 100;
}

tipAmount(40, 15);   // 6
tipAmount(80, 20);   // 16
(6).toFixed(2);      // "6.00"

15% of 40 is 40 × 15 ÷ 100 = 6. Because the function only does math, it is easy to test with many numbers.

NaN means "Not a Number". You get it from math on text that is not a number, such as Number("abc"). Number("") is 0, so an empty box needs its own check.

Separating "calculate" from "show on the page" is a habit that pays off in every bigger program.