Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to understand this code behaviour

Tags:

java

php

floor

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 .

like image 886
blisssan Avatar asked Jun 06 '26 16:06

blisssan


1 Answers

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.

like image 187
Peter Lawrey Avatar answered Jun 09 '26 05:06

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!