Jump to content

why this output is different..??


sanjay_zed

Recommended Posts

hello guys..!!! am new to this phpfreak community...i hav faced some problem while getting on floating point nos addition..if i use

echo (int)((0.1+0.7))*10;

i am getting output as 7. If i remove (int), i would get output as 8..which is correct...

for any other possibilities like ((0.1+0.2))*10 am getting correct output as 3..pls guys help me on this wid proper reason....waiting for solution....

Link to comment
Share on other sites

Did you come up with that scenario on your own? Because that is the exact example in the manual as to why you should not cast an unknown fraction as an integer: http://php.net/manual/en/language.types.integer.php See the 2nd warning down on the page.

 

And there is a link in that warning as to the reason for the error: http://www.php.net/manual/en/language.types.float.php#warn.float-precision

 

[Emphasis added]

Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118....
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.