Stuart's Useful C/C++ Pages

How do I change the precision of a number in std::cout?

In the old days of sprintf it was easy to change the precision (how many significant figures) to display numbers with. When using std::cout you need to use std::setprecision(x), where x is the number of significant figures required. As well as <iostream>, you will need to include <iomanip>

	
	
#include <iostream>
#include <iomanip>

int main {
double x = 3.1415927
std::cout << "Pi is " << std::setprecision(4) << x << std::endl;
}

This would display:

	Pi is 3.142