c++stringstream

Long stringstream LibXML string convert to floating point numbers adds unwanted digits


How can I modify the below code et cetera to produce the desired outcome?

I have a string with over 400 floating point numbers that I have been trying to put into a floating point array of 400 elements. I don't want to use sscanf because my statement would have explicit references to every single element.

With stringstream, I can do it more concisely, but I get extra trailing digits. I might be able to use bit operations to remove the unwanted digits.

Below is a testcase that hopefully encapsulates what I am trying to do.

    #include <iostream>
    #include <sstream>
    #include <stdio.h>

    using namespace std;

    int main(){
      float a, b, c;
      std::string str = "123456.780 234567.8 345678.912";
      std::stringstream s(str);
      s.setf(std::ios::fixed);

      s.precision(2);
    
      s >> a >> b >> c;
      printf ("a = %f, b = %f, c = %f\n",a,b,c);

      return 0;
    }
    Output:
    a = 123456.781250, b = 234567.796875, c = 345678.906250

I tried using setprecision, precision, and width without success.


Solution

  • In C or C++ language, float commonly is IEEE-754 binary32 format which has only 24 bits in its mantissa which allows for about 7 decimal digits (ref.). That means that any number having 8 digits or more could display a wrong value. And you want 6 digits in the integer part + 2 in the fractional part => a wrong value for the second digit after the decimal point is to be expected.

    What can be done?