Re: Convert float to double - weird failure



tugboat90 wrote:

I am trying to cast a float to a double (in C++) and am using the
static cast functionality. However, the value returned from the
static cast is not correct.

Example:
// Define a float
float f = 1.20000;

// Cast into a double - after the cast, the value of "d" is
// is "1.20000498297"
double d = static_cast<double> (f);

Is there some reason why the last few places are filled with garbage
now? I would have thought it would have been filled with 0's.

Yes. floats (and doubles) are based on binary representations, and
in your system they cannot exactly represent the value of 1.2.
Thus the value of f is set to the closest float approximation to
1.2 available. Now d is set to that value (not 1.2) whatever it
is.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>



--
Posted via a free Usenet account from http://www.teranews.com

.



Relevant Pages

  • Re: Convert float to double - weird failure
    ... I am trying to cast a float to a double and am using the ... static cast is not correct. ... When you trunc that string at 24 bits (including the initial ... more "0" bits and convert that string to 12 digits), ...
    (comp.programming)
  • Convert float to double - weird failure
    ... I am trying to cast a float to a double and am using the ... static cast functionality. ... static cast is not correct. ... Is there some reason why the last few places are filled with garbage ...
    (comp.programming)