1

Here:

#include <iostream>
#include <cstdlib>
#include <boost/lexical_cast.hpp>

int main(void) {
    const char * str = "277499.84";

    std::cout << boost::lexical_cast<double>(str) << std::endl;
    std::cout << strtof(str, NULL) << std::endl;
    std::cout << strtold(str, NULL) << std::endl;
    std::cout << atof(str) << std::endl;

    return 0;
}

output:

277500
277500
277500
277500

Why the output are not 277499.84?

kaylum
  • 13,833
  • 2
  • 22
  • 31
superK
  • 3,932
  • 6
  • 30
  • 54

1 Answers1

3

It's not the operations themselves losing accuracy, but the output.

You can use the I/O manipulator std::setprecision to control the numeric precision. The following will use the full precision of a double (assuming the stream is set for decimal output).

double value = boost::lexical_cast<double>(str);
std::cout << std::setprecision( std::numeric_limits<double>::digits10 + 1 ) << value;

Or you can use std::ios_base::precision. This is useful if you want to restore the precision to the original value after.

auto old_precision = cout.precision( std::numeric_limits<double>::digits10 + 1 );
cout << value;
cout.precision( old_precision );
paddy
  • 60,864
  • 6
  • 61
  • 103