php / php-src

The PHP Interpreter
https://www.php.net
Other
37.95k stars 7.73k forks source link

floatval return negative zero #11834

Closed RandUser123sa closed 1 year ago

RandUser123sa commented 1 year ago

Description

The following code:

<?php
echo floatval(sprintf("%1.2f", -0.0002));

Resulted in this output:

-0

But I expected this output instead:

// Acording to https://en.wikipedia.org/wiki/Signed_zero should be 0
0

PHP Version

8.1.21

Operating System

Ubuntu 22.04

iluuu1994 commented 1 year ago

I checked both C and JavaScript which behave identically to PHP (with printf and toFixed, respectively). What in https://en.wikipedia.org/wiki/Signed_zero specifically makes you believe that 0 is correct? After all, IEEE 754 allows representing both 0 and -0, and a negative number is "closer" to -0.

damianwadley commented 1 year ago

I'm trying to remember what and when, probably a bug report from a couple years ago, but there is precedent for PHP deliberately showing negative zero as "0"...

KapitanOczywisty commented 1 year ago

@damianwadley Not sure if this is it, but I remember number_format change in 7.2 https://3v4l.org/J9lGm

PR #2220 was "declined", but shortly followed by RFC and implemented in #2508 . However number_format was presented in RFC as "human-readable" format, so initial rejection could be still valid for the current issue.

alecpl commented 1 year ago

The ticket is confusing. The code uses sprintf and floatval. I don't see how floatval(-0.00) and floatval("-0.00") returning float(-0) would be wrong.

So, it must be about expectations for sprintf, right? This is what the ticket is about:

var_dump(sprintf('%.1f', -0.01));
var_dump(number_format(-0.01, 1));

returning:

string(4) "-0.0"
string(3) "0.0"

Before PHP 7.2 it was:

string(4) "-0.0"
string(4) "-0.0"

So, the number_format's internal consistency fix made it not consistent with (s)printf, but it looks like it might have been intended. The RFC does not mention printf at all.

That being said, the OP should just use number_format, I suppose.

github-actions[bot] commented 1 year ago

No feedback was provided. The issue is being suspended because we assume that you are no longer experiencing the problem. If this is not the case and you are able to provide the information that was requested earlier, please do so. Thank you.