Forum Moderators: coopster

Message Too Old, No Replies

Float math problem

         

mcavic

2:14 am on May 1, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I seem to be having problems with the following calculation. The results a, b, and c should all equal 11945. I tried a similar example in C, and it worked. Can anyone explain this? I fixed it by using round(), but it's still curious.

<?php

$a = 1.1945 * 10000;
$b = floor($a);
$c = (int)$a;

print "a = $a, b = $b, c = $c\n";

[root@worf tmp]# php x
a = 11945, b = 11944, c = 11944

hakre

10:45 am on May 2, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



hi mcavic,

that's totally normal with php. float vars aren't very exact so this is why this fails. to pindown it a bit more, (int)(1.1945 * 10000) is 1944 as well.

this is because of how php handles variables internally. c is totally different here, so it's no wonder that this does not happen in c, too.

checkout the docs about float values to learn more:
[php.net...]

--hakre

mcavic

5:47 pm on May 2, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks for the answer. I was aware of the float precision problem, but it caught me by surprise. I expected PHP to round it automatically as it does when you convert the float to a string.