2.3 โ€” Decimal numbers (double)

๐Ÿ“˜ Chapter 2โฑ about 1 min readโœ๏ธ Beginner friendly
Read one box at a time. No rush.

double#

double holds numbers with a decimal point.

C++
double price { 4.99 };double gravity { 9.81 };double half { 0.5 };
Tip

Always write a decimal number with a point, like 2.0, even if it is a whole number. It tells C++ "this is a decimal".

float#

float is a smaller, less exact version of double. Write an f at the end of the number:

C++
float speed { 3.5f };
Good habit

Use double by default. Use float only when you have a good reason (like some game or graphics code).

Decimals are not perfect#

Computers store decimals in binary. Some numbers can't be stored exactly โ€” just like 1/3 can't be written exactly as 0.333...

C++
double x { 0.1 + 0.2 };std::cout << std::setprecision(17) << x;   // needs #include <iomanip>
Output
0.30000000000000004
Watch out

Do not use == to compare decimals. Tiny errors make "equal" numbers slightly different. Check if they are close instead.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press โ† / โ†’ to move between lessons, / to search.