Boost logo

Boost Users :

From: Digvijoy Chatterjee (digvijoy.c_at_[hidden])
Date: 2007-04-01 10:23:42


> Digvijoy Chatterjee schrieb:
> > ...
> > here is a simple program,
> > int main() {
> > double d=76.32;
> > std::string s = boost::lexical_cast<std::string>(d);
> > cout << s << endl;
> > }
> >
> > output
> > 76.319999999...
> >
> > a) am i doing something wrong ??
>
> I don't think so.
>
> > b) if this is not wrong s this standard behavior ??
> >
>
> I'd say so. Due to the binary representation not all numbers with a
> representation of a fixed amount of digits in our decimal system have
> such a representation in the computer. Lexical_cast internally uses
> standard streams, if they don't correct such things (and I don't know of
> any implemementation that'd do so), your output will look garbaged. Try
> adding std::cout << d << std::endl.

adding std::cout << d << std::endl; does prints it out correctly, it
calls setprecision with a default value of 6 which does rounding ,
I assume there is no way to play with setprecision and lexical_cast ,
or to a more general problem of rounding doubles to certain places of
decimals while converting them to strings, as u say
>not all numbers with a
> representation of a fixed amount of digits in our decimal system have
> such a representation in the computer.

 I switched to ostringstream ,which does the job for the moment,
because of setprecision (6) but the code now is not as succinct as
lexical_cast.

Thx
Digz


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net