Re: Bug in conversion to ingegers???



0.01F cannot be exactly represented as a floating point number. It is
actually equal to something like .00999999999etc. So, when you multiply it
by 100, you get .99999999999etc

As far as I can tell, the multiplcation is done using doubles, so
assigning that double to a float has it rounded to the nearest value in the
float range, which in this case, is 1.

However, when you cast it directly to an int, the decimal portion is
truncated, before it can be rounded up.

To demostrate this, change the line in the second block to

i = (int)(float) (100.0 * 0.01f);

And you will get the results you expect.

Just another of the reasons why floating point is evil.
--
--
Truth,
James Curran
[erstwhile VC++ MVP]

Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com

"Vladimir" <xozar@xxxxxx> wrote in message
news:etjejFyTFHA.2172@xxxxxxxxxxxxxxxxxxxxxxx
> Can anybody say me why...
>
> /*
> int i;
> float f;
>
> // Result is one.
> f = 100 * 0.01f;
> i = (int)f;
> MessageBox.Show(i.ToString());
>
> // Result is zero!!!
> i = (int)(100 * 0.01f);
> MessageBox.Show(i.ToString());
> */
>
>
>
>
>
>
>


.



Relevant Pages

  • Re: Good C Question | pointer problem
    ... int main{ ... This allocates an array of 100 chars and putting the result in ptr. ... This will give you 100/sizeof (float) entries. ... You did not store any floating point values at fpor fp ...
    (comp.programming)
  • Re: static_cast<unsigned int> question...
    ... > unsigned int test2; ... This is caused by the way the float type store number internally. ... floating point value to: ... This is also the reason why comparing two floating point values with the ...
    (comp.lang.cpp)
  • Re: docs for (double) related to (int) or ???
    ... double seems to be related to int. ... No double is a commonly used term for floating point representations. ... For instance, in C, a float may use two bytes of storage, while a double could use four bytes. ... With more bits, you have higher precision. ...
    (comp.lang.php)
  • Re: 0.0 versus 0.0f
    ... You said it treats it as a float rather than an int. ... the Microsoft C compiler does not complain about ... integer or floating point. ...
    (microsoft.public.vc.mfc)
  • Re: weird problem
    ... I already told you that the comparison between an integer and a float ... And now a question about something else: why do you use floating ... use then to copy a float into a char *1. ... binary representation doesn't resemble a string like "123.46343" ...
    (comp.lang.c)