Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 231
Sylvain Martens Avatar asked Dec 08 '25 18:12

Sylvain Martens


1 Answers

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

like image 152
Rain Avatar answered Dec 11 '25 09:12

Rain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!