rox
rox

Reputation: 565

Why negative zero does not compare equal to positive zero using bccomp in PHP?

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)
$

Upvotes: 2

Views: 720

Answers (2)

Viktor
Viktor

Reputation: 11

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.

Upvotes: 1

Jeremy
Jeremy

Reputation: 336

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"));

Upvotes: 1

Related Questions