Skip to content
FORGENO ADS GAMESUnlock all $8

JavaScript · Unit 2: Decisions, functions and loops · Lesson 6 of 6

Mini project: tip calculator

Time to build the logic of a tip calculator the way real programs are built: small functions that each do one job.

Opens this lesson in Code Academy. Lessons open one after another, and each unit opens when you pass the checkpoint quiz before it (you can take a checkpoint early to skip ahead). If this lesson is not open yet, the button shows you its unit on your map.

The idea

Time to build the logic of a tip calculator the way real programs are built: small functions that each do one job.

Money needs care, because 0.1 + 0.2 is not exactly 0.3 in JavaScript. A common fix is to round to cents: Math.round(amount * 100) / 100.

Each step is checked with several bills, including tricky ones, so think through your function before you run it.

Worked example

JavaScript

function roundCents(amount) {
  return Math.round(amount * 100) / 100;
}
console.log(roundCents(3.14159));
console.log(0.1 + 0.2);
console.log(roundCents(0.1 + 0.2));

It prints

3.14
0.30000000000000004
0.3

Key terms

Function
A named, reusable block of code that takes parameters and can return a value.
Operators
+ - * / and % (remainder). Multiplication and division happen first unless parentheses say otherwise.

Practise it in Code Academy

This is a project lesson. It has 4 exercises (multiple choice and write code from a prompt) and takes about 12 minutes. Every answer is checked as you go, and feedback names the exact mistake. Hints and the solution are there if you get stuck.

Every lesson is free: no ads, no lives and no paywall.