Re: Dumb Question - Casting

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Thu, Feb 18, 2010 at 10:50 AM, Ashley Sheridan
<ash@xxxxxxxxxxxxxxxxxxxx> wrote:
> On Thu, 2010-02-18 at 09:47 -0600, Chuck wrote:
>
>> Sorry, been doing heavy perl and haven't written any PHP in 3 years so a tad
>> rusty.
>>
>> Can someone explain why the second expression in this code snippet evaluates
>> to 7 and not 8?
>>
>> $a = (int) (0.1 +0.7);
>>
>> echo "$a\n";
>>
>> $x = (int) ((0.1 + 0.7) * 10);
>>
>> echo "$x\n";
>>
>> $y = (int) (8);
>>
>> echo "$y\n";
>
>
> It works as expected if you take out the int() parts in each line. I'm
> not sure why, but the use of int() seems to be screwing around with the
> results. That's why the first line outputs a 0.
>
> Thanks,
> Ash
> http://www.ashleysheridan.co.uk
>

Another fine example of floating point math.

<?php

$x = ((0.1 + 0.7) * 10);

echo "((0.1 + 0.7) * 10) === $x\n";
// ((0.1 + 0.7) * 10) === 8


var_dump(8 == $x);
// bool(false)

var_dump($x - (int) $x);
// float(1)

var_dump(8 - $x);
// float(8.8817841970013E-16)

?>

Andrew

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux