Cong Tran An
Cong Tran An

Reputation: 135

How to print out the number 78.125 with two digits after the decimal point as 78.13 in C++

My assignment involve printing out double numbers with 2 digits after the decimal point. In one of the example tests, I got the output is 78.125. My teacher taught me to use the setprecision function to print out the number

#include <iomanip> 
...some code
cout << fixed << setprecision(2);
cout << x /*the number*/

Normally this would do just fine. However the example output is 78.13 while the output of my code is 78.12. I can't figure out anyway to do this.

Upvotes: 2

Views: 187

Answers (1)

Bathsheba
Bathsheba

Reputation: 234875

The rounding behaviour of std::cout and std::setprecision is implementation defined.

C++11 clears up this mess by supplying a function called std::fesetround which you can call using

std::fesetround(FE_TONEAREST);

before your std::cout statement. See http://en.cppreference.com/w/cpp/numeric/fenv/feround for more details.

Upvotes: 3

Related Questions