-1

I am reading 5 lines which contain STRING, DOUBLE data. I am reading the string then deleting the last character which is the comma and then read the double. (in is an ifstream variable)

in >> format >> number;
format.erase(format.length() - 1);

However, when reading from the test data below, the 4th number is read as 23.489999999999998 (as shown in debugging and printing). How can I prevent this?

&&&&&&, 456
&&&&&&,&, 1000000
$&&&&.&&, 123.38
&&&.&&&, 23.49
&&&.&&&, 23.4999
&&&E, 45
Dan Cojocaru
  • 167
  • 9
  • That's not wrong reading. That's right reading, and possibly wrong printing it out afterwards. (It is correct printing, but apparently not what you want. If you want to always print a floating point value *exactly* as you read it, you'll have to just use a string.) – BoBTFish Jan 26 '17 at 20:26
  • 2
  • Show the code that are you using for debugging and printing. Specify what is the input, and what is your desired output – Rama Jan 26 '17 at 20:52
  • I think it is not a duplicate, He is asking how to prevent, not why that happens – Rama Jan 26 '17 at 21:05
  • @Rama understanding why it happens is the first (and a very important/necessary) step in preventing it. – Jesper Juhl Jan 26 '17 at 21:13
  • @JesperJuhl that's true! Just I'm not agree with the "exact" duplicate flag – Rama Jan 26 '17 at 21:20

1 Answers1

1

Floating point values do not have infinite precission - they are approximations.

Your value is being read just fine and converted to the nearest possible approximation that can be stored in a double.

You should spend some time reading What Every Computer Scientist Should Know About Floating-Point Arithmetic.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70