On Tue, Jul 24, 2012 at 1:01 AM, Kingsquare.nl - Robin Speekenbrink <
ro...@kingsquare.nl> wrote:

> Hi all,
> [...]
>


> Why does the last of the following examples lower my key to 18 BUT does
> the var dump of the float clearly state 'float(19)' as the actual value:

    <?php
>     [...]
>     $i =(float) 1.19;
>     $i -= 1;
>     $i *= 100;
>     var_dump($i);
>     $arr = array($i=>1);
>     var_dump($arr);
>     ?>
>

When displaying floating point numbers, PHP uses the precision config
option (http://php.net/precision) so as to shorten output (and to hide
rounding errors in some circumstances). If you increase precision to 17
digits or so (64-bit IEEE floating point numbers have a decimal precision
of around 15 to 17 digits), the var_dump will reveal that $i is actually
18.999999999999993.... When you use it as an array index, it ends up
converted to an integer, which is done by truncation. If instead you were
to convert $i to a string when using it as an index:

    array("$i" => 1);
    array((string)$i => 1);

you'd get a result more along the lines that you expect.

I do know this is not really an internals thing, but after fiddling with
> this for some time, i gave up (bug 32671 might relate to this)


It's central to what you see, but note that it was decided that the
behavior was correct; the bug was in the documentation.

Again, if i'm to be regarded as a traditional n00b, i understand as i've
> seen float / casting discussions before.
>

I think those were more of the "how should PHP handle this" rather than the
"why does it do this" variety. There is probably a more suitable venue for
your question than the internals list; perhaps the general usage list. I
can be a bit grumpy about these things, but from what I've seen, the PHP
community likes to be inclusive, so I doubt it's a big deal.

Reply via email to