Re: Dumb Question - Casting
| From: | Nathan Rixham | Date: | Thu, 18 Feb 2010 17:06:13 +0000 |
| Subject: | Re: Dumb Question - Casting | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-302178@lists.php.net to get a copy of this message | ||
Daniel Egeberg wrote:
> On Thu, Feb 18, 2010 at 16:47, Chuck <chuck.carson@gmail.com> 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