Gacek
Gacek

Reputation: 10322

Why PHP's float 0 (zero) is being displayed with sign?

In PHP, lets create a variable and set it value to 0:

$x = 0;
echo $x;

it would display 0. If one would multiply that by -1:

$x = -1 * $x;
echo $x;

we still see 0. But if $x is a float:

$x = 0;
$x = (float)$x;
$x = -1 * $x;
echo $x;

we would get the output: -0.

Why is that? Shouldn't zero be always displayed unsigned, regardless of its underlying type?

Upvotes: 5

Views: 240

Answers (2)

Patricia Shanahan
Patricia Shanahan

Reputation: 26185

Floating point zero is used for more than just absolute zero. It is used to represent tiny results, too small absolute magnitude even for subnormal numbers.

In some calculations, the sign of such numbers does matter. For example, it matters that 1/+0 is positive infinity, but 1/-0 is negative infinity. To make that work right, multiplying 0 by -1 gives -0.

For example, See W. Kahan's paper "Branch Cuts for Complex Elementary Functions or Much Ado About Nothing's Sign Bit".

Upvotes: 1

Rocki
Rocki

Reputation: 363

Because PHP typically uses the IEEE 754 double precision format for floating point numbers which consists of:

1) sign (1 bit)

2) exponent (11 bit)

3) fraction (52 bit)

If you multiply $x with -1 the sign bit is set.

Integers use the two complement where the most significant bit (MSB) determines the sign. The MSB is 0 if you multiply with 0.

See: https://en.wikipedia.org/wiki/Signed_zero

Upvotes: 1

Related Questions