5

When cout-ing a number with floating points, i.e. 31.14159, how can I set cout to use the setprecision(4) on the floating point:

cout <<setprecision(4)<< 31.14159<<endl; // returns 31.14

As-is, it considers the whole number with its decimal digits, and outputs: 31.14. However, I want to get: 31.1416.

user3639557
  • 4,791
  • 6
  • 30
  • 55
  • possible duplicate of [Printing the correct number of decimal points with cout](http://stackoverflow.com/questions/5907031/printing-the-correct-number-of-decimal-points-with-cout) – Arun A S Apr 22 '15 at 05:41

2 Answers2

5

std::fixed says that there will be a fixed number of decimal digits after the decimal point.

std::cout << std::setprecision(4) << std::fixed << 31.14159;

- this will print 31.1416

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
Rishit Sanmukhani
  • 2,159
  • 16
  • 26
  • I was trying to understand 'setprecision' by adding 2 doubles, the addition had '0' in the decimal part. and the answer printed using 'cout< – Anuj Apr 30 '16 at 07:10
1

You can use std::fixed

std::cout << std::fixed << std::setprecision(4) << 31.14159 << endl ;

and you will get output as 31.1416

When you add std::fixed, the std::setprecision(4) will take effect on the decimal part, and thus you will get 4 values after the decimal point.

A std::setprecision() will take effect on the entire number. But when you add a std::fixed along with it, the std::setprecision() will effect only the decimal part of the number.

Arun A S
  • 6,421
  • 4
  • 29
  • 43
  • I was trying to understand 'setprecision' by adding 2 doubles, the addition had '0' in the decimal part. and the answer printed using 'cout< – Anuj Apr 30 '16 at 07:06