1

I'm doing my ICT homework and I ran into this problem: the decimals keep on getting rounded off when I print them. I've already included the <iomanip> header and used the fixed and setprecision manipulators, but it still keeps getting rounded off. Here's my code:

#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
     double num1 = 3.12345678
     
     cout << fixed << setprecision (4);

     cout << num1 << endl;

     return 0;
}

When I run the program, "3.1235" comes out instead of "3.1234," which is the expected output according to my teacher. How do I prevent the fourth decimal from rounding off?

  • 2
    That’s a question you’ll need to ask your teacher, since the answer your code is getting is the correct/expected one. – Konrad Rudolph Oct 24 '21 at 14:26
  • Does this answer your question? [Does setprecision in c++ round? If so why am I seeing this?](https://stackoverflow.com/questions/10922366/does-setprecision-in-c-round-if-so-why-am-i-seeing-this) – DasElias Oct 24 '21 at 14:30

3 Answers3

2

3.1234 is not the expected output, setprecision will round to the specified precision.

One solution to get 3.1234 is to round to the desired number of decimal places yourself (std::trunc just rounds towards zero):

#include <cmath>
...
std::cout << std::fixed << std::setprecision(4);
std::cout << std::trunc(num1 * 10000) / 10000 << endl;
qz-
  • 674
  • 1
  • 4
  • 14
2

If you want to prevent rounding i.e. you want to see more precision, you can use a higher value with setprecision.

If you want to round towards zero instead of rounding towards nearest, you can use the FE_TOWARDZERO rounding mode.

eerorika
  • 232,697
  • 12
  • 197
  • 326
2

Expanding answer of @eerorika. You can use std::fesetround() to set rounding strategy, as in code below. It outputs 3.1234 as you wished. Possible values for this function's argument are FE_DOWNWARD, FE_TONEAREST, FE_TOWARDZERO, FE_UPWARD.

Try it online!

#include <iostream>
#include <iomanip>
#include <cfenv>

int main() {
    double num = 3.12345678;
    std::fesetround(FE_TOWARDZERO);
    std::cout << std::fixed << std::setprecision(4) << num << std::endl;
}

Output:

3.1234
Arty
  • 14,883
  • 6
  • 36
  • 69