Lesson 31 of 296
Numbers and maths operators
What you will learn
- The maths operators
- The order JavaScript does maths in
- Shortcuts for changing a number
- Turning text into numbers
- Rounding and the Math object
- Decimal errors and how to avoid them
On this page
Maths operators
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Add | 10 + 3 | 13 |
- | Subtract | 10 - 3 | 7 |
* | Multiply | 10 * 3 | 30 |
/ | Divide | 10 / 4 | 2.5 |
% | Remainder | 10 % 3 | 1 |
** | Power | 2 ** 3 | 8 |
The remainder operator %
% gives what is left over after dividing. 10 % 3: 3 goes into 10 three times (9), and 1 is left over.
Common uses:
| Use | Code |
|---|---|
| Is a number even? | n % 2 === 0 |
| Is a number odd? | n % 2 !== 0 |
| Divisible by 3? | n % 3 === 0 |
| Last digit of a number | 1234 % 10 gives 4 |
| Seconds left after full minutes | 125 % 60 gives 5 |
| Loop back to the start of a list of 5 | (position + 1) % 5 |
Trap: the result keeps the sign of the left number. -5 % 2 is -1, not 1. So check odd numbers with !== 0, not === 1.
Order of operations
JavaScript does maths in the same order as school maths (often remembered as BODMAS or BIDMAS):
- Brackets
( ) - Powers
** - Multiply, divide and remainder
* / %, from left to right - Add and subtract
+ -, from left to right
2 + 3 * 4 14 (multiply first)
(2 + 3) * 4 20 (brackets first)
10 - 4 - 3 3 (left to right)When in doubt, add brackets. They make your intention clear to readers too.
Shortcuts
| Shortcut | Same as |
|---|---|
x += 5 | x = x + 5 |
x -= 5 | x = x - 5 |
x *= 2 | x = x * 2 |
x /= 2 | x = x / 2 |
x++ | x = x + 1 |
x-- | x = x - 1 |
These only work with let, because they change the variable.
Division by zero
10 / 0 Infinity
-10 / 0 -Infinity
0 / 0 NaNJavaScript does not crash; it gives these special values. Your code should check for them.
Turning text into numbers
Data from forms and URLs always arrives as strings. You must convert it before doing maths.
| Method | "42" | "42.5" | "42px" | "abc" | "" |
|---|---|---|---|---|---|
Number(x) | 42 | 42.5 | NaN | NaN | 0 |
parseInt(x, 10) | 42 | 42 | 42 | NaN | NaN |
parseFloat(x) | 42 | 42.5 | 42 | NaN | NaN |
Number()is strict: the whole string must be a number.parseInt()andparseFloat()read numbers from the start and stop at the first character that is not part of a number.- Always pass
10as the second argument toparseInt, to say "base 10" (normal numbers). - Note:
Number("")gives0, which can hide a bug with empty form fields.
Checking for NaN
Number.isNaN(x)Do not write x === NaN. It is always false, because NaN is the only value in JavaScript that is not equal to itself.
Rounding and the Math object
Math is a built-in object with maths tools.
| Code | Result | Meaning |
|---|---|---|
Math.round(4.5) | 5 | Nearest whole number |
Math.floor(4.9) | 4 | Round down |
Math.ceil(4.1) | 5 | Round up |
Math.trunc(-4.9) | -4 | Remove the decimal part |
Math.abs(-7) | 7 | Remove the minus sign |
Math.max(3, 9, 2) | 9 | The biggest |
Math.min(3, 9, 2) | 2 | The smallest |
Math.sqrt(16) | 4 | Square root |
Math.random() | e.g. 0.6213 | A random number from 0 up to (not including) 1 |
A random whole number from 1 to 6 (a dice):
const roll = Math.floor(Math.random() * 6) + 1;Rounding to 2 decimal places for display:
const price = 12.3456;
price.toFixed(2); "12.35" (a string, not a number)toFixed returns a string. It is for showing numbers, not for more maths.
Decimal errors
0.1 + 0.2 0.30000000000000004Computers store numbers in binary (0s and 1s). Some decimals, such as 0.1, cannot be stored exactly in binary, so tiny errors appear. This happens in most programming languages, not only JavaScript.
For money, store whole pence (or cents), not pounds with decimals:
const priceInPence = 1099; £10.99
const total = priceInPence * 3; 3297 pence, exactConvert to pounds only when you show it to the user.
Common mistakes
- Doing maths on form values without converting them first.
parseIntwithout the10.- Comparing with
NaNusing===. - Storing money as decimals.
- Using
toFixedand then doing more maths with the string result.
How to say it in an interview
"JavaScript has one number type for integers and decimals, based on 64-bit floating point, so values like 0.1 plus 0.2 are not exact. For money I store integer pence. I convert strings from inputs with Number, or parseInt with a radix of 10, and check for NaN with Number.isNaN, since NaN is not equal to itself. The remainder operator keeps the sign of the left operand, so I test odd numbers with not equal to zero."
Key words
| Word | Meaning |
|---|---|
| Operator | A symbol that does an operation, like + |
| Remainder | What is left after dividing, from % |
| Order of operations | The order maths is done in |
| Increment / decrement | Add 1 (++) / subtract 1 (--) |
| Parse | Read text and turn it into another type |
| NaN | "Not a Number": the result of invalid maths |
| Floating point | The way computers store decimal numbers, with small errors |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.