$include_dir="/home/hyper-archives/boost-users/include"; include("$include_dir/msg-header.inc") ?>
Subject: Re: [Boost-users] [conversion] Using Lexical_cast to convert string to float
From: Steven Watanabe (watanabesj_at_[hidden])
Date: 2009-06-09 23:17:25
AMDG
Ryan McConnehey wrote:
> In writing some unit tests to convert strings to floats I've come 
> across a puzzling situation.  I was trying to test that a 
> std::bad_cast was thrown if a number was too large to fit into a 
> float.  The error wasn't thrown but the float was given 1.#INF000.  
> The work around I used was to cast to a double and then do a 
> numeric_cast on the result.  This provided an exception for values 
> larger than could fit in a float.  Lexical_cast on a double though 
> works as I would have expected.  If a value is too large to fit into a 
> double then a std::bad_cast is called.
>
> float     test     = 
> boost::lexical_cast<float>("3.4e050");                                
> //test will have the value of 1.#INF000
> float     test     = boost::numeric_cast<float>( 
> boost::lexical_cast<double>("3.4e50");     //std::bad_cast is thrown
> double    test     = boost::lexical_cast<double>("3.4e350");          
>                      //std::bad_cast is thrown
>
> Is the lexical_cast for float behaving correctly?
The problem is in the standard library.  (Tested with msvc 9.0 
express--gcc 4.3.0 behaves sensibly).
#include <iostream>
#include <sstream>
int main() {
    {
        std::istringstream ss("3.4e050");
        float val;
        ss >> val;
        std::cout << std::boolalpha << "ss: " << static_cast<bool>(ss) 
<< ", val: " << val << std::endl;
    }
    {
        std::istringstream ss("3.4e350");
        double val;
        ss >> val;
        std::cout << std::boolalpha << "ss: " << static_cast<bool>(ss) 
<< ", val: " << val << std::endl;
    }
}
ss: true, val: 1.#INF
ss: false, val: -9.25596e+061
In Christ,
Steven Watanabe