Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,892 questions

51,823 answers

573 users

How to format floating point (double) in cout in C++

2 Answers

0 votes
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
	double pi = 3.14159;

	cout << "pi = " << setprecision(1) << pi << endl;
	cout << "pi = " << setprecision(2) << pi << endl;
	cout << "pi = " << setprecision(3) << pi << endl;
	cout << endl;
	cout << "pi = " << fixed << setprecision(1) << pi << endl;
	cout << "pi = " << fixed << setprecision(2) << pi << endl;
	cout << "pi = " << fixed << setprecision(3) << pi << endl;

	return 0;
}

/*
run:

pi = 3
pi = 3.1
pi = 3.14

pi = 3.1
pi = 3.14
pi = 3.142

*/

 



answered Feb 17, 2016 by avibootz
edited Feb 18, 2016 by avibootz
0 votes
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
	double pi = 3.14159;

	cout << "pi = " << setprecision(4) << pi << endl;
	cout << "pi = " << setprecision(5) << pi << endl;
	cout << "pi = " << setprecision(9) << pi << endl;
	cout << endl;
	cout << "pi = " << fixed << setprecision(4) << pi << endl;
	cout << "pi = " << fixed << setprecision(5) << pi << endl;
	cout << "pi = " << fixed << setprecision(9) << pi << endl;

	return 0;
}

/*
run: 

pi = 3.142
pi = 3.1416
pi = 3.14159

pi = 3.1416
pi = 3.14159
pi = 3.141590000

*/

 



answered Feb 17, 2016 by avibootz
...