Search code examples
c++floating-pointtruncateroundingfractions

Truncate float so as to have only two decimals


C++

I would like to cout float f = 2.3333, but only with two decimals. How do I do that? I remember something like this, but it doesn't work:

cout << f:2 << endl;

Solution

  • Using stream manipulators fixed and setprecision:

    #include <iomanip>
    
    float f = 2.3333;
    std::cout << std::setprecision(2) << std::fixed << f;