Numbers

Many languages have one type for whole numbers and another for decimals. JavaScript has just one number type. 42, 3.5 and -0.001 are all numbers.

Because of this, division always gives the exact answer. 7 / 2 is 3.5, not 3. The ** operator raises a number to a power, and you can put underscores in long numbers to make them easier to read:

console.log(7 / 2);
console.log(2 ** 10);
console.log(1_000_000);
console.log(1 / 0);

Output:

3.5
1024
1000000
Infinity

2 ** 10 means 2 multiplied by itself 10 times. The underscores are only for people, so 1_000_000 is printed without them. Dividing by zero does not stop the program. It gives a special number, Infinity.

Decimals are not always exact

JavaScript stores every number in binary (using only 0 and 1). Most decimal fractions, such as 0.1, have no exact binary form. So JavaScript stores a value that is very close, but not exact:

console.log(0.1 + 0.2);

Output:

0.30000000000000004

This is not a bug in JavaScript. Python and Java give the same result, because they store decimals the same way. For measurements and most math, the tiny error does not matter. For money, count in whole cents instead of decimal dollars.

When you show a decimal to a person, round it at the end with toFixed. The number in the parentheses is how many digits you want after the decimal point:

const price = 19.999;
console.log(price.toFixed(2));
console.log(typeof price.toFixed(2));

Output:

20.00
string

toFixed(2) rounds to two decimal places and adds zeros if needed. The second line uses typeof, which tells you the type of a value. It shows that toFixed gives you text (a string), not a number. Use it to show a number, not to calculate with it. You will learn more about typeof and strings in the next lessons.

In the exercise, print four numbers: a multiplication, a division, a power, and a price with two decimal places.