0

I take in a double and divide it by 1000, then output it to 5 decimal places. However, rounding occurs and I'm not sure how to make sure it doesn't.

    double dbl1;
    cout << "Enter: ";
    cin >> dbl1;
    dbl1 = dbl1 / 1000;
    cout << "Out: " << fixed << setprecision(5) << dbl1;

Input: 1.24768.

Expected: 0.00124.

Output: 0.00125.

ReignOfComputer
  • 747
  • 2
  • 10
  • 30
  • 2
    It seems you expect truncation. According to "mathematical rounding rules", the output seems to be more appropriate. This with a grain of salt: 1st. `double` doesn't fully behave like Real numbers. 2nd `` `round()` resembles "mathematical rounding" only partly (AFAIK). – Scheff's Cat Feb 03 '18 at 08:18
  • 1
    May be, this link for further reading [SE: What causes floating point rounding errors?](https://softwareengineering.stackexchange.com/q/101163). – Scheff's Cat Feb 03 '18 at 08:20
  • 1
    Floating-point arithmetic is intended to be approximate. What you are asking for requires **exact** mathematics; the decision about whether to use one digit or another occurs when the value crosses a **single point**. So, unfortunately, you are attempting to use floating-point arithmetic for a purpose it was not intended for. What is your real problem? If you just want to format a number the user enters, it might be better to do it with integer arithmetic or with strings of characters. If you are just doing approximate arithmetic, then an approximate solution could be okay. – Eric Postpischil Feb 03 '18 at 13:48
  • 1
    An approximate solution might be to output `dbl1 / 1000 - .000005` (with some modifications in case `dbl1` can be very small or negative). If you really want an exact solution, and your C++ implementation properly converts `double` to strings (some do not use full precision when formatting), then a correct method would be to convert `double` to a string containing a fixed-format decimal numeral with full precision, then simply use the first five post-decimal-point digits in the string. (E.g., if the conversion to string produced “12345.6789057913…”, you would use “12345.67890”.) – Eric Postpischil Feb 03 '18 at 13:51
  • 1
    (“Full” precision is actually not needed; you just need enough to ensure that no value such as x.xxxx79999999… is printed as “x.xxxx800000…” Some analysis would be required to determine the minimum number of digits needed.) – Eric Postpischil Feb 03 '18 at 13:55

0 Answers0