PHP 8 float decimal point different than PHP 7
Asked Answered
F

1

3

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?

Fa answered 5/11, 2021 at 19:51 Comment(2)
"however I am getting incorrect floating points." --> Perhaps now you are getting the better result, but your code relied on the prior less correct result. Better to use monetary calculation to the smallest unit (e.g. to the penny rather than the dollar).Lanky
FYI, 3v4l.org is a great sandbox for comparing behaviour across versions, as it runs in every version and compares the result for you. For example: 3v4l.org/1MZSTMuch
S
4

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

Sleeper answered 6/11, 2021 at 1:36 Comment(1)
Thanks I think this has helped getting on the right path to debug my issue. I changed the line to be ini_set('serialize_precision', ini_get("precision")); "precision" being 14 and not 16Fa

© 2022 - 2024 — McMap. All rights reserved.