Connecting Tech Pros Worldwide Help | Site Map

echo (int) (100 * (7.77 - 7 )); Why 76 ?

  #1  
Old March 18th, 2008, 07:55 PM
Gert Kok
Guest
 
Posts: n/a
echo (100 * (7.77 - 7 )); --77
echo (int) (100 * (7.77 - 7 )); --76

Why the difference?
  #2  
Old March 18th, 2008, 08:35 PM
PaulB
Guest
 
Posts: n/a

re: echo (int) (100 * (7.77 - 7 )); Why 76 ?


Gert Kok wrote:
Quote:
echo (100 * (7.77 - 7 )); --77
echo (int) (100 * (7.77 - 7 )); --76
>
Why the difference?
http://uk3.php.net/manual/en/language.types.float.php

Read the warning.

Paul

--
Add an underscore after the p to reply


  #3  
Old March 18th, 2008, 10:05 PM
C. (http://symcbean.blogspot.com/)
Guest
 
Posts: n/a

re: echo (int) (100 * (7.77 - 7 )); Why 76 ?


On 18 Mar, 19:30, "PaulB" <pb...@ntlworld.comwrote:
Quote:
Gert Kok wrote:
Quote:
echo (100 * (7.77 - 7 )); --77
echo (int) (100 * (7.77 - 7 )); --76
>
Quote:
Why the difference?
>
http://uk3.php.net/manual/en/language.types.float.php
>
Read the warning.
>
This is not a PHP thing - most computer languages are like this except
for ones which deal with maths rather than arithmetic.

C.
  #4  
Old March 19th, 2008, 07:45 PM
sheldonlg
Guest
 
Posts: n/a

re: echo (int) (100 * (7.77 - 7 )); Why 76 ?


Gert Kok wrote:
Quote:
echo (100 * (7.77 - 7 )); --77
echo (int) (100 * (7.77 - 7 )); --76
>
Why the difference?
int(76.9999999999999 ) ==76 (truncation)

while
76.9999999999999 shown with no decimal places is rounded to 77

This is the same as in C, C++, Java, Fortran, Basic, etc. etc. etc.

Basically, there is no way to EXACTLY store a repeating decimal in 32
bits. Floating numbers (decimal points) are approximations. The casting
with (int) truncates this approximation.
Closed Thread