Search code examples
c++precisioncoutiomanip

How to use setprecision in cpp for only the number of floating points


When cout-ing a number with floating points, i.e. 31.14159, how can I set cout to use the setprecision(4) on the floating point:

cout <<setprecision(4)<< 31.14159<<endl; // returns 31.14

As-is, it considers the whole number with its decimal digits, and outputs: 31.14. However, I want to get: 31.1416.


Solution

  • std::fixed says that there will be a fixed number of decimal digits after the decimal point.

    std::cout << std::setprecision(4) << std::fixed << 31.14159;
    

    - this will print 31.1416