php-src icon indicating copy to clipboard operation
php-src copied to clipboard

`number_format` no longer round properly big float

Open kylekatarnls opened this issue 2 years ago • 27 comments

Description

The following code:

<?php

echo number_format(1599828571.23561241, 6, '.', '');

Resulted in this output:

1599828571.235613

But I expected this output instead:

1599828571.235612

This is the result with PHP < 8.4 and it sounds good to me either we consider round() or floor() as the best operation to use.

Context: precision matters in my case, as I aim to support float timestamp (possibly more precise than microseconds) then to round them as close as possible and in a consistent manner.

PHP Version

8.4 (master 2024-05-26)

Operating System

Both Ubuntu and Windows

kylekatarnls avatar May 26 '24 12:05 kylekatarnls

From where I stand it's hard to understand why fixing round broke the number_format case above and why we need to choose one or the other. Shouldn't it just be correct in both case?

kylekatarnls avatar Jul 13 '24 16:07 kylekatarnls

From where I stand it's hard to understand why fixing round broke the number_format case above and why we need to choose one or the other. Shouldn't it just be correct in both case?

To clarify: what has been changed is the internal function _php_math_round(), and this is used from PHP's round() and number_format() (and some others).

Now inside _php_math_round() was a guard expression:

https://github.com/php/php-src/blob/10a94f846d39f8726031afa7ecbed72409e1a769/ext/standard/math.c#L168-L171

The comment is apparently not correct, otherwise https://3v4l.org/YbUMA wouldn't happen. So the 1e15 has been replaced by 1e16. Is this the best (or proper) solution? Frankly, I don't know (I'm not an expert on IEEE 754), but having round($x, 0) returning a number with decimals is obviously wrong, and in my opinion worse than the reported behavior. I'm still not happy about the BC break in a minor version, but apparently that cannot be avoided, and after all, IEEE 754 double arithmetic cannot be really exact.

cmb69 avatar Jul 13 '24 16:07 cmb69

This seems like a BUG to me: https://3v4l.org/a9Wol vs https://3v4l.org/a9Wol/rfc#vgit.master

cristicotet avatar Oct 21 '24 06:10 cristicotet

@cristicotet, indeed that is a bug, namely that you use floating point to calculate monetary values. Look at https://3v4l.org/oXVqK. The problem is not the rounding, but rather that result is less than 0.675 (even that simple number can't be represented exactly as binary floating point value). From there on, everything goes south. Instead use precise rational numbers, and then be very explicit about finally rounding (there might be relevant tax laws on how to handle such cases).

Anyhow, I don't think it makes sense to keep this ticket open. Nobody proposed an RFC when there still was some time (maybe), and RC2 is already out.

cmb69 avatar Oct 21 '24 10:10 cmb69

@cmb69 Can you give more details on the RFC process?

Because the RFC which was linked in this thread was https://wiki.php.net/rfc/change_the_edge_case_of_round and it has a "Declined" status. So my expectation is that nothing would change between PHP 8.3 and 8.4 if there is no accepted RFC to actually change the rounding.

kylekatarnls avatar Oct 21 '24 12:10 kylekatarnls

Actually, the changed behaviour on master seems correct to me: https://3v4l.org/al7HZ/rfc#vgit.master

mvorisek avatar Oct 21 '24 12:10 mvorisek

@kylekatarnls, it is correct that https://wiki.php.net/rfc/change_the_edge_case_of_round had been declined. However, that would have been a pretty big change; although possibly a reasonable one. (It seems to me that PHP puts in too much effort to have binary floats working like true decimals.) Anyhow, that doesn't mean that minor changes can't happen. And in this case it's about #12222 (see https://github.com/php/php-src/issues/14332#issuecomment-2226994886 for further details).

Now, to revert a commit, it is not necessary to have an RFC, but there needs to be some consensus; that wasn't the case in the discussion; it seems to me that only few actually considered to revert the commit. And I still think the old behavior is a bug.

Anyhow, the actual problem you are facing is not the rounding, but rather that ext/date sometimes treats microseconds as floats. Particularly, ::createFromTimestamp() should not have been accepting a float, but rather a string, or two ints. The latter would have been trivial to implement (there is already php_date_initialize_from_ts_long()), and precise. Prior to RC1, something like the following could have been applied:

 ext/date/php_date.c         |  20 ++++++++++++++++----
 ext/date/php_date.stub.php  |   4 ++--
 ext/date/php_date_arginfo.h | Bin 69343 -> 69416 bytes
 3 files changed, 18 insertions(+), 6 deletions(-)

diff --git a/ext/date/php_date.c b/ext/date/php_date.c
index 95a5e5ae73..831202f247 100644
--- a/ext/date/php_date.c
+++ b/ext/date/php_date.c
@@ -2703,11 +2703,14 @@ PHP_METHOD(DateTime, createFromInterface)
 PHP_METHOD(DateTime, createFromTimestamp)
 {
 	zval         *value;
+	zend_long    microseconds = 0;
 	zval         new_object;
 	php_date_obj *new_dateobj;
 
-	ZEND_PARSE_PARAMETERS_START(1, 1)
+	ZEND_PARSE_PARAMETERS_START(1, 2)
 		Z_PARAM_NUMBER(value)
+		Z_PARAM_OPTIONAL
+		Z_PARAM_LONG(microseconds)
 	ZEND_PARSE_PARAMETERS_END();
 
 	php_date_instantiate(execute_data->This.value.ce ? execute_data->This.value.ce : date_ce_date, &new_object);
@@ -2715,7 +2718,10 @@ PHP_METHOD(DateTime, createFromTimestamp)
 
 	switch (Z_TYPE_P(value)) {
 		case IS_LONG:
-			php_date_initialize_from_ts_long(new_dateobj, Z_LVAL_P(value), 0);
+			if (microseconds < 0 || microseconds > 999999) {
+				zend_argument_value_error(2, "must be between 0 and 999999");
+			}
+			php_date_initialize_from_ts_long(new_dateobj, Z_LVAL_P(value), microseconds);
 			break;
 
 		case IS_DOUBLE:
@@ -2778,11 +2784,14 @@ PHP_METHOD(DateTimeImmutable, createFromInterface)
 PHP_METHOD(DateTimeImmutable, createFromTimestamp)
 {
 	zval         *value;
+	zend_long    microseconds = 0;
 	zval         new_object;
 	php_date_obj *new_dateobj;
 
-	ZEND_PARSE_PARAMETERS_START(1, 1)
+	ZEND_PARSE_PARAMETERS_START(1, 2)
 		Z_PARAM_NUMBER(value)
+		Z_PARAM_OPTIONAL
+		Z_PARAM_LONG(microseconds)
 	ZEND_PARSE_PARAMETERS_END();
 
 	php_date_instantiate(execute_data->This.value.ce ? execute_data->This.value.ce : date_ce_immutable, &new_object);
@@ -2790,7 +2799,10 @@ PHP_METHOD(DateTimeImmutable, createFromTimestamp)
 
 	switch (Z_TYPE_P(value)) {
 		case IS_LONG:
-			php_date_initialize_from_ts_long(new_dateobj, Z_LVAL_P(value), 0);
+			if (microseconds < 0 || microseconds > 999999) {
+				zend_argument_value_error(2, "must be between 0 and 999999");
+			}
+			php_date_initialize_from_ts_long(new_dateobj, Z_LVAL_P(value), microseconds);
 			break;
 
 		case IS_DOUBLE:
diff --git a/ext/date/php_date.stub.php b/ext/date/php_date.stub.php
index d0119aac88..a2741776dd 100644
--- a/ext/date/php_date.stub.php
+++ b/ext/date/php_date.stub.php
@@ -368,7 +368,7 @@ public static function createFromInterface(DateTimeInterface $object): DateTime
     public static function createFromFormat(string $format, string $datetime, ?DateTimeZone $timezone = null): DateTime|false {}
 
     /** @tentative-return-type */
-    public static function createFromTimestamp(int|float $timestamp): static {}
+    public static function createFromTimestamp(int|float $timestamp, int $microseconds = 0): static {}
 
     /**
      * @return array<string, int|array>|false
@@ -479,7 +479,7 @@ public static function __set_state(array $array): DateTimeImmutable {}
     public static function createFromFormat(string $format, string $datetime, ?DateTimeZone $timezone = null): DateTimeImmutable|false {}
 
     /** @tentative-return-type */
-    public static function createFromTimestamp(int|float $timestamp): static {}
+    public static function createFromTimestamp(int|float $timestamp, int $microseconds = 0): static {}
 
     /**
      * @return array<string, int|array>|false
diff --git a/ext/date/php_date_arginfo.h b/ext/date/php_date_arginfo.h
index 8ce0114206..af17806ac9 100644
Binary files a/ext/date/php_date_arginfo.h and b/ext/date/php_date_arginfo.h differ

But now it's likely too late. :(

cmb69 avatar Oct 21 '24 13:10 cmb69