0

I am having trouble getting my program to output the correct precision for my doubles. Say I have a

double d;

After running some algorithm, I get d as my output. I want to set the precision of my d variable to 4 points of precision after decimal. I should be able to do this like so:

cout << setprecision(4) << d;

The problem is that if I if d is an integer, then no decimal placed are printed.

For example, if d == 120, then my program will print 120. I want it to print 120.0000 instead. How do I get my program to always print 4 decimal places?

Strikeskids
  • 3,932
  • 13
  • 27
  • possible duplicate of [Correct use of std::cout.precision() - not printing trailing zeros](http://stackoverflow.com/questions/17341870/correct-use-of-stdcout-precision-not-printing-trailing-zeros) – 5gon12eder Jul 04 '15 at 14:21
  • Why was this question down-voted so much? Isn't it perfectly clear and valid? It has been asked (probably more than once) before, however. – 5gon12eder Jul 04 '15 at 14:22

1 Answers1

3

You need to be using fixed precision to output a fixed number of decimal points. You should to tell the stdout stream (cout) that you want to use fixed precision.

std::cout << std::fixed << std::setprecision(4) << d;
Strikeskids
  • 3,932
  • 13
  • 27