Search code examples
c++stringdoubleatof

atof() returning float instead of double


I have text files containing numbers with precision upto 12 decimal places.

So to load the number into a c++ vec I wrote this

void txt2vec(const std::string& file, std::vector<double>& data)
{
std::string line;
std::ifstream myfile(file);
if (myfile.is_open())
{
    while ( getline (myfile,line) )
    {

        std::cout << atof(line.c_str()) << std::endl;
        //data.push_back(atof(line.c_str()));
    }
    myfile.close();
}
}

atof should return a double but I am getting float

This is the output of the program

 -0.0340206
 -0.0873645
  0.0789533
  0.115022
  0.0809852
  0.118469
  0.113328
  0.112746
 -0.0331071

where as it should be

  -0.0340205617249
  -0.0873644948006
   0.078953281045
   0.115022487938
   0.0809852406383
   0.118468873203
   0.11332821846
   0.112745501101
  -0.0331071354449

Solution

  • You are likely getting the expected values, but you are not printing the full precision in your shown code.

    The << operator for output streams and doubles has a default precision of 6 for general use and readability. See std::ios_base::precision.

    The default precision, as established by std::basic_ios::init, is 6.

    If you want to display the full number you need to set the precision with the number of digits a double may contain, e.g. use numeric_limits.

    std::cout << -0.0340205617249 << std::endl; // -0.0340206
    std::cout.precision(std::numeric_limits<double>::digits10 + 1);
    std::cout << -0.0340205617249 << std::endl; // -0.0340205617249
    

    See also std::setprecision.