Re: Dumb Question - Casting

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

 



Daniel Egeberg wrote:
> On Thu, Feb 18, 2010 at 16:47, Chuck <chuck.carson@xxxxxxxxx> 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";
>>
> 
> The reason why you get 7 instead of 8 is because you are using
> floating point arithmetic. 0.1 (i.e. the fraction 1/10) does not have
> a finite representation in base 2 (like you cannot finitely represent
> 1/3 in base 10). So the number 0.1 is represented in the computer as a
> number that is strictly less than 0.1 so when you do 0.1+0.7=x then
> you have x<0.8 in the computer (think 7.9999999...). When you cast to
> int you just truncate the number, i.e. you chop off the fractional
> part leaving you with 7.
> 

yup as Daniel pointed out; this is correct - love floats & casting!

see:

$y = ((0.1 + 0.7) * 10);
$x = (int)$y;
$z = intval($y);
var_dump($y);
var_dump(serialize($y));
var_dump($x);
var_dump($z);

outputs:
float(8)
string(55) "d:7.99999999999999911182158029987476766109466552734375;"
int(7)
int(7)

lovely! - note: serializing gives us the exact value of the float

regards,

Nathan



-- 
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