Search code examples
phpnumber-formatting

number_format gives wrong output while using DECIMAL_POINT as constatnt for decimals parameter


I have defined constant in codeigniter constants.php file.

defined('DECIMAL_POINT') or define('DECIMAL_POINT','2');

And using it to format number as below example.

$number=1000000;
$amount = number_format($number,DECIMAL_POINT, '.', '');
echo $amount;

Output is: 1000000.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

The output should be 1000000.00;

It was working fine before I updated my PHP version to 8.2.8


Solution

  • As noted by CBroe in a comment, DECIMAL_POINT is a reserved constant in PHP 8.2.0+, and it has a value that you don't expect.

    One solution to avoid this issue is to define your own constant and add a prefix, so that the risk of PHP adding a constant with this name in a future version is lowered:

    define('APP_DECIMAL_POINT', 2);
    

    I didn't use defined('APP_DECIMAL_POINT') or define('APP_DECIMAL_POINT','2'); because it's better to have an error if our code try to redefine an existing constant, than silently declaring the constant with a value that can be totally different.

    Then you can use:

    $number = 1000000;
    $amount = number_format($number, DECIMAL_POINT, '.', '');
    echo $amount;
    

    Try it online on 3v4l