2

I try comparing "+0.00000000000" with "+0.00000000000" using bccomp. I expect the result to be 0, but actually get a 1.

$ cat bcmath.php
<?php
var_dump(bccomp("+0.00000000000","-0.00000000000"));
?>

$ php bcmath.php
int(1)
$
rox
  • 525
  • 7
  • 16
  • 1
    I believe that this is fixed in PHP 7.1.10: http://www.php.net/ChangeLog-7.php#7.1.10, which fixed a number of `bcmath` bugs, including this one: https://bugs.php.net/bug.php?id=46781 – Thijs Riezebeek Oct 02 '17 at 13:49

2 Answers2

1

Are you comparing +0 with +0, or +0 with -0. A '1' is returned when the left operand is larger than the right. A '-1' is returned when the right operand is larger than the left. A '0' is returned when they are equal. If comparing a positive on the left with a negative on the right it will return '1'.

var_dump(bccomp("+0.00000000000","-0.00000000000"));
Jeremy
  • 326
  • 4
  • 15
1

From an ordinary arithmetic point of view, -0, 0 and +0 are all the same. In computing tho, some operations can have different behaviors.

For example if you try

if (-0 == +0) 

You will get TRUE

bccomp seems to be one of the cases that differentiate between a positive zero and a negative zero.

In all honesty I do not know why exactly does it behave like that, I just know that it does, so if you are writing a program that relies on comparison using bccomp (and returning 0 when comparing a negative zero to a positive one) you might want to run an "if" check beforehand.

Viktor
  • 11
  • 3
  • I just found that bccomp("+0","-0") gets a 0, but bccomp("+0.0","-0.0") gets 1. Really odd. – rox Apr 21 '16 at 06:53
  • Yep. All the while if you compare them with 'if (+0.0 == -0.0)' or even 'if (+0.00 == -0.0000)' You will still get a TRUE out of it – Viktor Apr 21 '16 at 11:26