Boost logo

Boost :

From: renato_boost (renatius_at_[hidden])
Date: 2002-02-28 13:29:42


Hi,

would it be acceptable if it is instead the floating point value to
be wrapped in an helper class?
I was thinking something like:

struct float_var
    {
    enum { default_precision = 6 };
    enum display_fmt { fixed, scientific, default };
    };

template <class T>
struct float_var_T : public float_var
    {
    explicit float_var_T
        (
        T Val,
        std::streamsize Precision,
        display_fmt Fmt
        )
        : value ( Val )
        , precision ( Precision )
        , format ( Fmt )
        {
        }

    T value;
    std::streamsize precision;
    display_fmt format;
    };

template <class Ch, class Tr, class T>
std::basic_ostream<Ch, Tr> & operator <<
    (
    std::basic_ostream<Ch, Tr> & os,
    float_var_T<T> const & var
    )
    {
    os << std::setprecision( var.precision );

    if ( var.format == float_var::scientific )
        os << std::scientific;
    else if ( var.format == float_var::fixed )
        os << std::fixed;

    os << var.value;

    return os;
    }

template <class T>
float_var_T<T> make_float_var
    (
    T value,
    std::streamsize precision = 6,
    float_var::display_fmt format = float_var::default
    )
    {
    return float_var_T<T>( value, precision, format );
    }

int main()
    {
    double number = 123.897654319;

    std::cout << boost::lexical_cast<std::string>( make_float_var
(number, 14, float_var::fixed) ) << std::endl;
    }

Cheers,

Renato Mancuso

--- In boost_at_y..., Jon Wang <webmaster_at_b...> wrote:
> Hi,
>
> The expected output of the following code should be "123.1234567".
>
> #include <boost/lexical_cast.hpp>
> //...
> std::string s = boost::lexical_cast<std::string>(123.1234567);
> std::cout<<s<<std::endl;
>
> But only can we get "123.123", for the std::stringstream uses the
default precision. Is this a problem? If so, how can we fix it?
>


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk