Pergunta

In php I am displaying a number that I am making red if it is negative and green otherwise:

if ($daysAhead>=0) $class = "ahead";
else $class = "behind";
echo "<span class=\"$class\">$daysAhead</span>";

I have a number that is displaying as green and it prints as -0.

Why is it displaying the negative sign? Why is -0>=0 evaluating as true?

Foi útil?

Solução

I found a webpage that discusses the concept of negative zero:

http://hype-free.blogspot.com/2008/12/negative-zero-what-is-it.html and http://en.wikipedia.org/wiki/%E2%88%920_(number)

Turns out I was rounding the number to the nearest decimal. so .009 was rounding to .0 but it was also negative.

It also turns out in php floatval(-0.0)==0.

This prompted me to write some very peculiar code:

if ($daysAhead==0){  
    $daysAhead=0;
}
if ($daysAhead>=0) $class = "ahead";
else $class = "behind";
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top