Namespaces
Variants
Views
Actions

std::setprecision

From cppreference.com
< cpp‎ | io‎ | manip
Revision as of 21:53, 22 September 2022 by Xmcgcg (Talk | contribs)

 
 
 
Input/output manipulators
Floating-point formatting
setprecision
Integer formatting
Boolean formatting
Field width and fill control
Other formatting
Whitespace processing
Output flushing
(C++20)  

Status flags manipulation
Time and money I/O
(C++11)
(C++11)
(C++11)
(C++11)
Quoted manipulator
(C++14)
 
Defined in header <iomanip>
/*unspecified*/ setprecision( int n );

When used in an expression out << setprecision(n) or in >> setprecision(n), sets the precision parameter of the stream out or in to exactly n.

Contents

Parameters

n - new value for precision

Return value

An object of unspecified type such that

  • if out is an object of type std::basic_ostream<CharT, Traits>, the expression out << setprecision(n)
    • has type std::basic_ostream<CharT, Traits>&
    • has value out
    • behaves as if it called f(out, n)
  • if in is an object of type std::basic_istream<CharT, Traits>, the expression in >> setprecision(n)
    • has type std::basic_istream<CharT, Traits>&
    • has value in
    • behaves as if it called f(in, n)

where the function f is defined as:

void f(std::ios_base& str, int n)
{
    // set precision
    str.precision(n);
}

Example

#include <iostream>
#include <iomanip>
#include <cmath>
#include <limits>
 
int main()
{
    const long double pi = std::acos(-1.L);
    std::cout << "default precision (6): " << pi << '\n'
              << "std::setprecision(10): " << std::setprecision(10) << pi << '\n'
              << "max precision:         "
              << std::setprecision(std::numeric_limits<long double>::digits10 + 1)
              << pi << '\n';
}

Output:

default precision (6): 3.14159
std::setprecision(10): 3.141592654
max precision:         3.141592653589793239

Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
LWG 183 C++98 setprecision could only be used with streams
of type std::ostream or std::istream
usable with any
character stream

See also

changes formatting used for floating-point I/O
(function) [edit]
manages decimal precision of floating point operations
(public member function of std::ios_base) [edit]