0

I am inputing some decimal data from a file using ifstream. The double column that I am using changes the decimal values itself.

Example if the value in file is 0.714000 it will be changed to 0.71399999999999997. What can I do to keep the value same as the file.

while (getline(infile, line)) {
    string error_message = "";
    std::cout << std::fixed << std::setprecision(6);
    double decimal_value=0.0
    istringstream ss(line);
    ss >> decimal_value;

decimal_value variable should have 0.714000 instead of 0.71399999999999997 ,as I am using these values for some maths calculations and this small difference changes the final equation result.

shahmeer arhsad
  • 49
  • 1
  • 2
  • 8
  • 3
    Floating point numbers are (almost) always approximations. Nothing you can do about that. See : [why are floating point numbers inaccurate](https://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate). In fact there is a lot of theory about how to estimate and minimize those errors in calculations (numerical methods) – Pepijn Kramer Jul 31 '22 at 11:46
  • Print with a lower precision and it will round to nearest. – QuentinUK Jul 31 '22 at 11:58
  • One thing you may do is to use ```string``` instead of ```double```. – anas16 Jul 31 '22 at 12:02
  • Similar to 1/3 = 0.33333333333333333333333333333333333 ... you can use more digits but never actually be exact. For even more digits use:- https://www.boost.org/doc/libs/1_79_0/libs/multiprecision/doc/html/boost_multiprecision/tut/floats/fp_eg/floatbuiltinctor.html – QuentinUK Jul 31 '22 at 12:08
  • The value `0.714000` cannot be exactly represented in IEEE-754 `double` format; the two values that *can* be represented, either side of that, are (approximately) `0.71399999999999997` and `0.71400000000000008`. It seems that your input value is converting to the closest value, which is just below that required. You can maybe try adjusting the FP rounding mode, if you *know* that you always want the value just higher. – Adrian Mole Jul 31 '22 at 13:37

0 Answers0