JavaScript AcademyProfessional Engineering
Level 1 · FoundationsModule 2: Variables, Values and TypesLesson 8 of 150About 45 minutes

Lesson 8: Numbers and mathematical operations

01Opening question

Why might a shop's checkout show $0.30000000000000004 instead of $0.30, and how do professionals avoid it?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

The raw total has many decimals. toFixed(2) turns it into a string with exactly two decimals for display.

const price = 19.99;
const quantity = 3;
const total = price * quantity;
console.log(total);
console.log(total.toFixed(2));

03Objective and prerequisites

Learning objective: Calculate with numbers using arithmetic operators, Math methods and rounding; recognise floating-point surprises, NaN and Infinity; and format money with toFixed.

You need: Lesson 3: Statements, expressions and comments, Lesson 6: Variables with let and const

Skills practised: Values and variables, Numbers and Math.

04Explanation

JavaScript has one main number type for whole numbers and decimals. The operators are + - * /, % (remainder) and (power): 2 3 is 8.

Decimals are stored in binary, so some results are slightly off: 0.1 + 0.2 is 0.30000000000000004. For money, round when you show the result, or calculate in cents (whole numbers).

Math is a built-in toolbox: Math.round, Math.floor (down), Math.ceil (up), Math.max, Math.min, Math.abs and Math.random() (a random decimal from 0 up to, but not including, 1).

Some calculations do not give a normal number. NaN means "not a number", for example "abc" * 2. Dividing by zero gives Infinity. Check results before you show them.

05Definitions

Number
JavaScript's numeric type for whole numbers and decimals.
Floating point
The binary way decimals are stored, which makes some results slightly inexact.
NaN
"Not a Number": the result of a calculation that has no numeric answer.
Math
A built-in object with mathematical functions such as Math.round and Math.max.
toFixed
Formats a number as a string with a fixed number of decimals.
Exponent operator (**)
Raises a number to a power: 3 ** 2 is 9.

Open the full glossary

06Visual learning object

Mathematical expression evaluator. Try expressions with , /, % and * and see the grouping and each sub-result.

Loading the interactive object…

Open the full Mathematical expression evaluator page with its guided experiment.

07Examples

ex-008-01Arithmetic operators Browser-executable JavaScript

The six operators cover most calculations. % gives the remainder, ** the power.

console.log(7 + 2, 7 - 2, 7 * 2, 7 / 2);
console.log(7 % 2);
console.log(2 ** 10);
console.log((7 + 3) / 2);
Sample input
None
Expected output
9 5 14 3.5 1 1024 5
Common mistake
Using ^ for powers. In JavaScript ^ is bitwise XOR; use **.
Try this
Use % to test whether 15 is divisible by 5 (the remainder is 0).
Source
examples/ex-008-01-arithmetic.js (repository pending publication)

ex-008-02Floating-point surprises Browser-executable JavaScript

Binary decimals cause tiny errors. Round for display, or work in whole cents.

console.log(0.1 + 0.2);
console.log((0.1 + 0.2).toFixed(2));
const priceCents = 1999;
const totalCents = priceCents * 3;
console.log(totalCents / 100);
Sample input
None
Expected output
0.30000000000000004 0.30 59.97
Common mistake
Comparing money with === after decimal arithmetic.
Try this
Calculate 3 × 0.1 in cents and print the result in dollars.
Source
examples/ex-008-02-floating-point.js (repository pending publication)

ex-008-03The Math toolbox Browser-executable JavaScript

Math methods round, compare and pick numbers.

console.log(Math.round(4.5), Math.floor(4.9), Math.ceil(4.1));
console.log(Math.max(12, 40, 7), Math.min(12, 40, 7));
console.log(Math.abs(-15));
const dice = Math.floor(Math.random() * 6) + 1;
console.log(dice >= 1 && dice <= 6);
Sample input
None
Expected output
5 4 5 40 7 15 true
Common mistake
Forgetting + 1, which gives dice values from 0 to 5.
Try this
Simulate a coin flip: print 0 or 1 using Math.random and Math.floor.
Source
examples/ex-008-03-math-toolbox.js (repository pending publication)

ex-008-04NaN and Infinity Browser-executable JavaScript

Some operations have no normal numeric result. Check with Number.isNaN before showing a value.

const bad = "abc" * 2;
console.log(bad);
console.log(Number.isNaN(bad));
console.log(10 / 0);
console.log(NaN === NaN);
Sample input
None
Expected output
NaN true Infinity false
Common mistake
Testing value === NaN, which is always false.
Try this
Print the result of Math.sqrt(-1) and check it with Number.isNaN.
Source
examples/ex-008-04-nan-and-infinity.js (repository pending publication)

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Fix the price display

Format a floating-point result for display.

const price = 0.1;
const quantity = 3;
const total = price * quantity;
console.log("Total: $" + total);

Split the bill

Use Math.ceil to split a bill fairly into cents.

const bill = 100;
const people = 3;
// TODO: each person's share, rounded UP to the next cent
const share = bill / people;
console.log("Each pays:", share);

Temperature and distance converter

Write formulas with the right precedence and round the results.

// Convert 30 °C to Fahrenheit: F = C × 9 / 5 + 32
// Convert 10 km to miles: miles = km × 0.621371, rounded to one decimal

09Prediction

Commit to an answer first, then run the real code to compare.

console.log(10 % 3);
console.log(Math.round(2.5));
console.log(Math.floor(-2.5));
console.log((1.25).toFixed(1));

What are the four lines?

10Debugging investigation

The discounted price shows NaN

A sale page should show the price after a 20% discount: 80. It shows NaN.

const price = 100;
const discountPercent = "twenty";
const salePrice = price - price * discountPercent / 100;
console.log("Sale price:", salePrice);

More cases in the Debugging Detective Laboratory

11Practical scenario

Splitting a restaurant bill

The Tip Calculator project divides a bill with a tip between friends. Rounding each share up to the next cent makes sure the restaurant is never short, and the tests check exactly this rule.

const total = 115;
const people = 3;
const share = Math.ceil(total * 100 / people) / 100;
console.log(share);

12Knowledge check

1. What does this print?

console.log(2 ** 3);
  • 8
  • 6
  • 9
  • 5

2. Why is 0.1 + 0.2 not exactly 0.3?

  • A bug in the browser
  • Decimals are stored in binary and some cannot be represented exactly
  • The + operator rounds
  • Numbers are strings

3. What does this print?

console.log(Math.floor(4.7));
  • 4
  • 5
  • 4.7
  • 5.0

4. This should check for an invalid result but never does. Why?

const result = "x" * 2;
if (result === NaN) console.log("invalid");
  • NaN cannot be stored
  • NaN is never equal to anything, even itself
  • === only works with strings
  • isNaN must be in capitals

5. What type does toFixed return?

console.log(typeof (3.14159).toFixed(2));
  • number
  • string
  • boolean
  • undefined

6. Which is safer for adding many prices?

  • Add the decimal prices and round at the end
  • Convert to whole cents, add, then convert back
  • Both are identical
  • Use strings

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Fix the price display: Prints Total: $0.30; Uses toFixed(2)
  • Split the bill: Prints Each pays: 33.34; share is 33.34; Uses Math.ceil
  • Temperature and distance converter: Prints both conversions; Inputs are the given values; Results are calculated
  • ex-008-01: output matches the documented expected output
  • ex-008-02: output matches the documented expected output
  • ex-008-03: output matches the documented expected output
  • ex-008-04: output matches the documented expected output

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-01-foundations/module-02-variables-values-and-types/lesson-008-numbers-and-mathematical-operations/. Every example on this page is generated from those files.

The GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Academy) has not been published yet, so these links will work once it is. Until then, use the ZIP download above.

15Summary and next steps

  • + - / % * cover arithmetic; precedence follows maths.
  • Decimal results can be slightly inexact: round for display or use cents.
  • Math provides rounding, max/min, abs and random.
  • NaN and Infinity signal impossible results; test NaN with Number.isNaN.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation Floating point for beginners
Context: I saw 0.1 + 0.2 = 0.30000000000000004.
Task: Explain why with a simple analogy (like writing 1/3 in decimal).
Constraints: No binary maths beyond one example.
Expected behaviour: I can explain why money uses cents.
Testing: Give me two calculations to try in the playground that show the effect.
Code prediction Math method quiz
Context: I know round, floor, ceil, max, min and abs.
Task: Ask me eight questions, including negative numbers.
Constraints: Wait for my answers before explaining.
Expected behaviour: Each has one exact answer.
Testing: Explain floor versus round for negatives.
Debugging Wrong rounding
Context: My bill split gives 33.33 each, so the total is 99.99 instead of 100.
Task: Help me design a rounding rule that never undercharges.
Constraints: Hints only; I write the code.
Expected behaviour: Shares add up to at least the bill.
Testing: Suggest three bills and party sizes to test.
Exercise generation Number exercises
Context: I completed the converter exercise.
Task: Create two exercises using Math methods and toFixed with real-world contexts.
Constraints: Exact expected output, no functions yet.
Expected behaviour: Each uses at least two Math methods.
Testing: Include the expected output.
Code review Money handling review
Context: I wrote a script that totals five decimal prices with tax.
Task: Review where rounding happens and whether it is consistent.
Constraints: Do not rewrite; list problems with line numbers.
Expected behaviour: Rounding happens once, at a clear point.
Testing: Suggest a test case that would expose any problem.