Skip to content

Incorrect round($num, 0, PHP_ROUND_HALF_UP) result for $num = 1.4999999999999998 / 4503599627370495.5 #12143

@TimWolla

Description

@TimWolla

Updated description:

<?php
$number = 0.49999999999999994;
var_dump($number, round($number, 0, PHP_ROUND_HALF_UP));

$number = 1.4999999999999998;
var_dump($number, round($number, 0, PHP_ROUND_HALF_UP));

$number = 4503599627370495.5;
var_dump($number, round($number, 0, PHP_ROUND_HALF_UP));

Resulted in this output:

float(0.49999999999999994)
float(1)
float(1.4999999999999998)
float(2)
float(4503599627370495.5)
float(4503599627370495.5)

But I expected this output instead:

float(0.49999999999999994)
float(0)
float(1.4999999999999998)
float(1)
float(4503599627370495.5)
float(4503599627370496)

see: https://3v4l.org/jsMKb


Description

Old Description

The following code:

<?php

var_dump(round(0.49999999999999994, 0, PHP_ROUND_HALF_UP), 0.49999999999999994);

Resulted in this output:

float(1)
float(0.49999999999999994)

But I expected this output instead:

float(0)
float(0.49999999999999994)

see: https://3v4l.org/d6AK6 / https://3v4l.org/VvInn


Extracted from #12056 (comment) into a dedicated issue. The solution consists of using modf() and then explicitly checking against 0.5, instead of adding or subtracting 0.5, since the result of the addition / subtraction might not be exactly representable.

/cc @jorgsowa Are you interested in developing the fix?

PHP Version

8.2.10

Operating System

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions