CodeBlanks Logo Icon CodeBlanks

Floating-point types

Learn float, double and long double types.

Floating-point types

C++ has three floating-point types: float (single precision, ~7 digits), double (double precision, ~15 digits) and long double (extended, ~18+ digits).

When writing a float value, use the f suffix: float temp = 36.5f;. Without the suffix, 36.5 is a double.

For most calculations double is recommended; precision loss is small and there is no performance penalty on modern CPUs. Choose float when memory savings matter.

float and double precision

float holds about 7 significant digits; double about 15. So printing float x = 3.14159265f; may lose some digits.

In scientific and financial calculations, small errors accumulate; that is why double is the safe choice. Do not trust floating-point equality: 0.1 + 0.2 may not exactly equal 0.3.

You can control the number of printed digits with std::setprecision (from <iomanip>); you will see it at an advanced level.

Practice Print float and double

Inside main, declare a float (value 36.5f) and a double (value 3.14159265). Print both on separate lines with std::cout using std::endl.

Starter code

main.cpp
#include <iostream>

int main() {
    // Declare float and double
    // Print each with std::cout
    return 0;
}

Sample solution

main.cpp
#include <iostream>

int main() {
    // Declare float and double
    float temperature = 36.5f;
    double precise = 3.14159265;
    // Print each with std::cout
    std::cout << temperature << std::endl;
    std::cout << precise << std::endl;
    return 0;
}

Expected output

36.5
3.14159

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Double-precision variable

Question
____ precise = 3.14159265;
Answer
double precise = 3.14159265;

Explanation: double offers about 15 digits of precision.

2 Which is the highest-precision floating type?

  • int
  • float
  • double
  • long double Correct answer

Explanation: long double offers the widest precision.

3 Match floating types

Term Meaning
float ~7 digits
double ~15 digits
long double ~18+ digits
f suffix float marker

All lessons in Beginner