c++boostlexical-cast

Enable boost::lexical_cast to throw out of range error for values smaller than double range


boost::lexical_cast throws errors for values larger than the maximum value of double. But for numbers smaller than minimum value, it silently makes it zero. How do I enable out of range errors for later case(i.e. If a number is smaller than 2.22507e-308, then parser should throw some error)?

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

int main()
{
    std::cout<<boost::lexical_cast<long double>("1.5787658476e-400")<<'\n';
    std::cout<<boost::lexical_cast<double>("1.5787658476e-400")<<'\n';
    std::cout<<std::numeric_limits<double>::min()<<'\n';

    try{
        std::cout<<boost::lexical_cast<double>("1.5787658476e+400")<<'\n';
    } catch(boost::bad_lexical_cast &e)
    {
        std::cout<<e.what()<<'\n';
    }
     std::cout<<std::numeric_limits<double>::max()<<'\n';

    return 0;
}

Solution

  • I think this is expected behaviour.

    You could check that the number roundtrips exactly. But in general decimal representations don't correspond exactly to a binary representation so it's gonna be tricky and impossible to get right in the general case (where any decimal input is valid).

    You could achieve better roundtrip safety using a decimal number type, like e.g. boost::multiprecision::cpp_dec_float.