Learning objective: Calculate with numbers using arithmetic operators, Math methods and rounding; recognise floating-point surprises, NaN and Infinity; and format money with toFixed.
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.
Numbers are IEEE 754 double-precision floats: integers are exact up to Number.MAX_SAFE_INTEGER (2^53 − 1); beyond that use BigInt. Decimal fractions such as 0.1 have no exact binary representation.
For currency, store integer minor units (cents) and convert for display, or use a decimal library. toFixed returns a string and uses round-half-to-even-like behaviour on binary values, so 1.005.toFixed(2) is "1.00".
NaN is the only value not equal to itself; test with Number.isNaN. Number.isInteger, Number.parseFloat and Intl.NumberFormat (locale-aware currency formatting) are the professional tools.
Operator precedence: binds tighter than unary minus is not allowed (-2 2 is a SyntaxError); * / % before + -. Increment operators ++/-- exist but are often avoided outside loops for clarity.
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.
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.
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
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.
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 explanationFloating 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 predictionMath 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.
DebuggingWrong 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 generationNumber 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 reviewMoney 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.