Re: Convert float to double - weird failure



On Oct 25, 9:10 pm, tugboat90 <bmsh...@xxxxxxxxx> wrote:
Hello all,

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.

Any help would be much appriciated. Thanks!

Round off error.

The float has only 24 significant bits. The double
has 53. The remaining bis will all be zeroes, and 1.2 in
binary is a repeating binary: 1.00110011001100110011...
When you trunc that string at 24 bits (including the initial
1), and then radix-convert that truncated string to decimal
but include more digits than just those first 6 (or append 29
more "0" bits and convert that string to 12 digits), you'll see
the other stuff pops out. That's because a truncated
repeating binary is just an approximation to the infinite,
exact repeating binary.

.



Relevant Pages

  • Re: Converting floats to Strings and back
    ... > I'm trying to convert a String to a float, do some arithmetic on it, then ... > The code works fine until I exceed 8 digits. ... the nasty things that happen with floating point, ...
    (comp.lang.java.programmer)
  • Re: Digits after the decimal point
    ... It struck me when we were being taught about a program which counts the ... number of digits in a given number. ... want to accept it in float datatype. ... You can read it into a string first, ...
    (comp.lang.c)
  • Re: Float to String
    ... The problem in that case was that values stored in an Oracle database ... For binary numbers having n bits following the binary point, n digits ... Subject: Float to String ...
    (comp.lang.ada)
  • Re: Convert float to double - weird failure
    ... tugboat90 wrote: ... I am trying to cast a float to a double and am using the ... static cast functionality. ... static cast is not correct. ...
    (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)