Division and Remainder
Division with / works as you would expect, and the result can be a decimal number:
console.log(3 / 2);
console.log(4 / 2);This prints:
1.5
2A whole number is printed without a decimal point: 2, not 2.0.
Decimal numbers are written with a dot: 1.5, never with a decimal comma (1,5), which is used in some countries. In JavaScript, a comma separates values, so console.log(1,5) doesn't print one and a half, but two numbers: 1 5.
Sometimes the last digit of a decimal result is a little off: 0.1 + 0.2 prints 0.30000000000000004. Computers store decimal numbers with a tiny inaccuracy. It's not a mistake in your program, so don't let it surprise you.
The operator % gives the remainder after division: what is left over when you divide whole numbers, as you learned in elementary school:
console.log(7 % 3);
console.log(10 % 5);This prints:
1
07 % 3 is 1, because 3 goes into 7 twice (2 × 3 = 6) and 1 is left over: 7 = 2 × 3 + 1. 10 % 5 is 0, because 5 goes into 10 exactly twice and nothing is left over.
% is often used to tell even and odd numbers apart. An even number divided by 2 leaves nothing, an odd number leaves 1:
console.log(8 % 2);
console.log(9 % 2);This prints:
0
1So a number is even when its remainder after dividing by 2 is 0. You'll use this in the next lesson, on conditions.
Instructions
Print the price of half a chocolate bar: chocolatePrice divided by 2.
How much money will you have left after buying as many chocolate bars as you can? It's the remainder after dividing money by chocolatePrice. Create a constant moneyLeft with this remainder, using %.
Using moneyLeft, print Money left: 10.
Is the price of a chocolate bar even or odd? Print the remainder after dividing chocolatePrice by 2.