3

Today i was working on a PHP project and came across this code behaviour

<?php
$x = 5.5;
$y = 0;
echo $z = floor($x * $y * -1);
?>

This gave the output of -0 . Can anyone shed light on why this echoes -0 . But I expected 0 Only when adding floor this appears to happen. I tried the same in java.

class Sample {
    public static void main(String[] args) {
        float x =5.5f;
        int y = 0;
        System.out.println(Math.floor(x*y*-1));
    }
}

This also prints -0.0 .

Alexis C.
  • 91,686
  • 21
  • 171
  • 177
blisssan
  • 628
  • 1
  • 8
  • 16
  • possible duplicate of [How can a primitive float value be -0.0? What does that mean?](http://stackoverflow.com/questions/6724031/how-can-a-primitive-float-value-be-0-0-what-does-that-mean) ... Hint for the next time: in addition to running another example in a different language ... do some prior research ... like on this site here to figure if that question has been asked before. And especially for anything that deals with "basic" language elements ... chances are **very** high that yes, somebody had the same problem before! – GhostCat Jul 30 '15 at 14:48
  • Because of `-1`. `floor(0.0*-1);` same result. – callmemath Jul 30 '15 at 14:52
  • Thank you. I do understand. Probably I didnt make use of proper search terms. But the behavior is what Im trying to understand. It happens only when I add floor. If I don't have floor on the statement it out puts 0 & not -0. – blisssan Jul 30 '15 at 14:54
  • You may want to cast the output of `floor` (which is a float) to an integer to avoid -0.0 to occur : `$z = intval(floor($x*$y*-1), 10);` or `$z = (int) floor($x*$y*-1);` – Mat Jul 30 '15 at 15:04
  • @Mat - Not sure about PHP but in Java you can just add `0.0` to make sure any `-0.0` becomes `0.0`. See [here](http://stackoverflow.com/a/8153449/823393). – OldCurmudgeon Jul 30 '15 at 15:10

2 Answers2

3

float and double have both a positive 0 and a negative 0. When you multiple 0 * -1 you get -0 as specified in the IEEE 754 standard.

Note: 1/0 is positive infinity but 1/-0 is negative infinity.

You can see that http://ideone.com/tBd41l

System.out.println(0f * -1);

prints

-0.0

Math.floor is not required.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

Because PHP's floor() returns a float (for some reason) and floats are allowed to have negative 0.

This gives a normal 0:

$x = 5.5;
$y = 0;
echo $z = floor($x * $y * -1 * -1);
mike.k
  • 3,277
  • 1
  • 12
  • 18