Numbers and Math
Work out totals, remainders and powers with JavaScript's arithmetic operators, in the order JavaScript does, and round money so it shows as dollars and cents.
Novice · JavaScript · Updated
After this lesson you can
- Calculate with + - * / % and ** in the order JavaScript works them out
- Round a money amount with Math.round or toFixed, and explain why 0.1 + 0.2 isn't exactly 0.3
Key takeaways
- JavaScript has one kind of number for whole numbers and decimals alike, written without quotes.
-
-
- / are plus, minus, times and divided by; % gives the remainder after dividing, and ** raises a number to a power.
-
-
- JavaScript works out parentheses first, then **, then * / % from left to right, then + and - from left to right.
- 0.1 + 0.2 gives 0.30000000000000004, because a computer can't store most decimals exactly.
- For money, round to cents with Math.round(amount * 100) / 100, and show two decimal places with toFixed(2).
A shopping cart adds up prices, a game adds points, a fitness app works out your pace, and a bill-splitting app shares a dinner check between friends. All of it is arithmetic, and in JavaScript it's done with a handful of symbols you mostly know from math class. This lesson also shows a surprise that has put wrong totals on real shopping carts, and how to keep money right.
Numbers
JavaScript has one kind of number, for whole numbers and decimals alike: 12, 4.75, -3. A number is written without quotes. With quotes, '4.75' is text that happens to hold digits, and Types and Converting Between Them shows why that difference matters.
const lattesSold = 12;
const lattePrice = 4.75;
console.log(lattesSold);
console.log(lattePrice);
12
4.75
The arithmetic operators, read aloud
A symbol that does something to values is an operator. These are the arithmetic operators:
| Operator | Read it | Example | Result |
|---|---|---|---|
+ |
plus | 4.75 + 3.25 |
8 |
- |
minus | 20 - 9.5 |
10.5 |
* |
times (the symbol is an asterisk) | 4.75 * 2 |
9.5 |
/ |
divided by (the symbol is a slash) | 10 / 4 |
2.5 |
% |
remainder (the symbol is a percent sign) | 17 % 5 |
2 |
** |
to the power of (two asterisks) | 2 ** 3 |
8 |
const lattePrice = 4.75;
console.log(lattePrice * 2);
console.log(20 - 9.5);
console.log(10 / 4);
console.log(17 % 5);
console.log(2 ** 3);
9.5
10.5
2.5
2
8
/ keeps the decimals: 10 divided by 4 is 2.5. 2 ** 3 is 2 × 2 × 2. JavaScript prints 9.5, not 9.50: a number has no idea it's money. Showing two decimal places comes at the end of this lesson.
Remainder: what's left over
A loyalty card at The Daily Grind holds 10 stamps, and a full card earns a free drink. A regular with 23 stamps has filled two cards. How many stamps are on the card in their wallet now?
That's a remainder: what's left after dividing as many whole times as you can. 10 goes into 23 twice (20), with 3 left over. % gives you the 3:
const stamps = 23;
const stampsPerCard = 10;
const onCurrentCard = stamps % stampsPerCard;
const stampsToGo = stampsPerCard - onCurrentCard;
console.log(onCurrentCard);
console.log(stampsToGo);
3
7
In your textbook % may be called the modulo or modulus operator, read "mod". Despite the symbol, it has nothing to do with percentages. It's also how programs tell even from odd: 14 % 2 is 0, and 15 % 2 is 1.
The order of operations
When an expression has more than one operator, JavaScript works it out in the order you learned in math class:
- parentheses first
- then
** - then
*,/and%, from left to right - then
+and-, from left to right
Two lattes and a muffin, with and without parentheses:
console.log(2 * 4.75 + 3.25);
console.log(2 * (4.75 + 3.25));
console.log(10 - 4 / 2);
console.log((10 - 4) / 2);
12.75
16
8
3
The first line is two lattes plus one muffin. The second, with parentheses, is two lattes and two muffins. Textbooks call this order operator precedence. When you're unsure, add parentheses: they cost nothing and make your meaning plain to the next reader.
Try it. Make a file named split.js. Four friends share a $38.60 order and want to add a 20% tip. Work out the total with the tip, then each person's share, and print both. (A 20% tip is the total times 0.20.)
The 0.1 + 0.2 surprise
Try this, and look closely at the answer:
console.log(0.1 + 0.2);
console.log(14.25 * 0.08);
0.30000000000000004
1.1400000000000001
It isn't a bug in JavaScript, and it isn't your mistake. Think of writing 1/3 as a decimal: 0.3333… goes on forever, so you stop somewhere and you're a tiny bit off. A computer stores numbers in binary (ones and zeros), and in binary most decimals, 0.1 among them, go on forever the same way. The tiny leftover shows up in the last digit. Textbooks call numbers stored this way floating-point numbers, and Python, C# and almost every other language behave the same.
For most things the leftover doesn't matter. For money, a receipt that says Sales tax: $1.1400000000000001 looks broken, so round.
Rounding with Math.round and toFixed
JavaScript has a built-in toolbox of math helpers called Math. Math.round(...), read "Math dot round", rounds the number in its parentheses to the nearest whole number. To round to cents, turn the dollars into cents, round, and turn them back:
console.log(Math.round(4.4));
console.log(Math.round(4.5));
const tax = 14.25 * 0.08;
const taxInCents = Math.round(tax * 100);
console.log(taxInCents / 100);
4
5
1.14
To show an amount with exactly two decimal places, use toFixed(2) after the number, read "to fixed 2". It rounds to that many places and fills in zeros:
const twoLattes = 4.75 * 2;
console.log(twoLattes);
console.log(twoLattes.toFixed(2));
console.log((0.1 + 0.2).toFixed(2));
9.5
9.50
0.30
toFixed hands back text, not a number, so use it last, when you print the amount. Keep calculating with numbers, rounded to cents with Math.round where it matters, such as tax.
Try it. In split.js, print each person's share with toFixed(2). Then print 1.1 * 3 on its own and see the floating-point leftover for yourself.
Check yourself
2 questions to try on the lesson page.
So what
Totals, tips, scores, timers and progress bars are all arithmetic. Knowing the order JavaScript works things out, and rounding money before anyone sees it, keeps your numbers right in front of real customers.
Key terms
- Number
- Arithmetic Operators
- Math Object
- Remainder Operator
- Operator Precedence
- Floating-Point Number