2

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.

Cong Tran An
  • 125
  • 6
  • 2
    Hmm, prints 78.13 with visual studio, but prints 78.12 [here](http://coliru.stacked-crooked.com/a/2e9ab9c875d15655). – wally Oct 05 '16 at 15:44
  • 1
    AFAIK the round up/down behavior is implementation defined. If that is the case you will have to manually round it yourself like they do [here](http://stackoverflow.com/questions/1343890/rounding-number-to-2-decimal-places-in-c) – NathanOliver Oct 05 '16 at 15:44
  • 1
    I would imagine [this question](http://stackoverflow.com/questions/11208971/round-a-float-to-a-given-precision) to be a better duplicate... –  Oct 05 '16 at 15:44
  • Note that 78.125 can be represented *exactly* in IEEE754 floating point. – Bathsheba Oct 05 '16 at 15:47
  • Yes, it can be represented exactly. But if the compiler uses a general algorithm to do the conversion, it may use the imprecise binary forms of 0.1, 0.01 and 0.001 to multiply 1, 2 and 5 and add things up to get some error. Is that possible? – Zhuoran He Oct 05 '16 at 15:49
  • 2
    You could also do out = round(x * 100) / 100; before outputting the number. – Steeve Oct 05 '16 at 15:52

1 Answers1

3

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Example, please? I can't get this to work [here](http://coliru.stacked-crooked.com/a/1384edecedc21010). – wally Oct 05 '16 at 16:03