c++lexical-cast

lexical_cast strtof strtold lose accuracy?


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?


Solution

  • 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 );