C++ iomanip Library - setprecision Function


Advertisements

Description

The C++ function std::setprecision behaves as if member precision were called with n as argument on the stream on which it is inserted/extracted as a manipulator (it can be inserted/extracted on input streams or output streams).

It is used to sets the decimal precision to be used to format floating-point values on output operations.

Declaration

Following is the declaration for std::setprecision function.

setprecision (int n);

Parameters

n − New value for the decimal precision.

Return Value

It returns unspecified. This function should only be used as a stream manipulator.

Exceptions

Basic guarantee − if an exception is thrown, the stream is in a valid state.

Data races

The stream object on which it is inserted/extracted is modified. Concurrent access to the same stream object may introduce data races.

Example

In below example explains about setprecision function.

#include <iostream>
#include <iomanip>

int main () {
   double f =3.14159;
   std::cout << std::setprecision(5) << f << '\n';
   std::cout << std::setprecision(9) << f << '\n';
   std::cout << std::fixed;
   std::cout << std::setprecision(5) << f << '\n';
   std::cout << std::setprecision(9) << f << '\n';
   return 0;
}

Let us compile and run the above program, this will produce the following result −

3.1416
3.14159
3.14159
3.141590000
iomanip.htm
Advertisements