Search code examples
c++variablesfloating-pointdoublevar

C++ double act as float?


C++

float f = 0.123456789;
double d = 0.123456789;

cout << "float = " << f << endl;
cout << "double = " << d << endl;

Output

float = 0.123457
double = 0.123457

Why?
How to use double and long double?
Is there a variable larger than long double?


Solution

  • What you're seeing is not exactly what the content of the variables is, but what the standard ouptut stream outputs after rounding them. Look up the std::setprecision function from the header <iomanip>.

    A quick test on Coliru with:

    float f = 0.123456789;
    double d = 0.123456789;
    
    std::cout << "float = " << std::setprecision(13) << f << std::endl;
    std::cout << "double = " << std::setprecision(13) << d << std::endl;
    

    yields the output:

    float = 0.1234567910433

    double = 0.123456789

    It shows that indeed, float and double are not the same type in terms of which numbers they can represent. (Hint: this is not even the exact number stored in the float, only the one rounded to 13 significant digits).