Search code examples
floating-pointprecisionphp-7.4php-8php-8.1

PHP 8 float decimal point different than PHP 7


I upgraded some accounting scripts to PHP 8.1 however I am getting incorrect floating points.

I loop a few transactions debit/credit and the balance is 0 however at the end when I try to compare to zero its not working with == 0 and === 0

After a few debugging I found out:

<?php
var_dump(1097.5 - 835.7);

returns float(261.79999999999995)

And the same line in PHP 7 returns float(261.8)

This can easily be tested using this sandbox

So I was wondering is there any settings I can change in my PHP configs to make sure I get the same floating results has before without having to go and round up at every stage in hundreds of scripts?


Solution

  • PHP 8.0 UPGRADE NOTES:

    var_dump() and debug_zval_dump() will now print floating-point numbers using serialize_precision rather than precision. In a default configuration, this means that floating-point numbers are now printed with full accuracy by these debugging functions.

    So you can change this

    ini_set('serialize_precision', 16);
    

    https://3v4l.org/uOAPD#v8.1rc3

    However, I doubt this is your real issue! since this change affect only "these debugging functions" and also serlization functions like serialize, json_encode