2

There's a huge concern regarding decimal to float conversion in PHP, because of precision issues.

I wonder why nobody talks about using the decimals as strings and do all the calcs in that way. It seems that PHP works pretty good that way:

"1.123456" / "1.123456"
"1.123456" * "1.123456"
"1.123456" + "1.123456"
"1.123456" - "1.123456"

All those work perfectly fine.

So, what are the cons?

By the way, Laravel's Collection has a method "sum", which might rely on strings to do the operation.

For instance:

// It does the math on MySQL
$orders = OrderModel::sum('total');

// It does the math on PHP, not on MySQL
$orders = OrderModel::get()->sum('total');

Laravel doesn't warn about this. And it seems nobody either. So I might assume is totally reliable.

John Smith
  • 1,848
  • 3
  • 13
  • 24
  • 2
    In your PHP examples, the strings get converted to floats so there is no effective difference whether you surround the string with quotes or not. Maybe you want to use something like https://www.php.net/manual/en/book.bc.php? – kmoser Aug 16 '22 at 03:29
  • Is this true? "Double precision (which PHP's float uses) doesn't fail until $70,368,744,177,664.01 (which also has .015625 for the cents). You have nothing to worry about." So, should I worry only if I manage amounts above 70 trillions? $70,368,744,177,664 ? – John Smith Aug 16 '22 at 03:38
  • 2
    Your questions seem to jump around. To your original question, per type juggling rules, strings or numerics would be [treated the same](https://3v4l.org/MLI1B). As to “failing”, IEEE 754 is generally about preferring to store either giant numbers or tiny fractional numbers, but is not for storing giant numbers with many decimal places, and you can “break” it [trivially](https://stackoverflow.com/a/588014/231316). There are ways to solve this, but it just depends on what you need to do. – Chris Haas Aug 16 '22 at 04:00
  • I might be jumping round, but the concern is the same: loosing precision. There's to much paranoia regarding doing math with floats, specially for financial purposes. Although it seems that unless you're dealing with huge numbers, using float in PHP shouldn't be risky. I wonder if there's a single case where using small numbers can cause issues. I haven't found any. – John Smith Aug 16 '22 at 17:54
  • This amount with 5 decimals works perfectly fine. 999,999,999.00001 So why people freak out with small numbers? – John Smith Aug 16 '22 at 18:13
  • @JohnSmith What do you mean by paranoia? The limits and pitfalls of floats are clearly documented, and that includes not just large numbers but operations that require precision to a large number of decimal places (for varying definitions of "large"). See Chris Haas' links for details. – kmoser Aug 16 '22 at 20:19

0 Answers0