0

If I use a bcmath function, they all take values as strings and return a string. I have several functions that use bcmath in order to work on monetary values. The database stores these values as a DECIMAL(15,3) in most cases.

Here is a code example below:

    public function get_payments_total(): string
    {
        $subtotal = '0.0';

        foreach($this->get_payments() as $payments)
        {
            if(!$payments['cash_adjustment'])
            {
                $subtotal = bcadd($payments['payment_amount'], $subtotal);
            }
        }
        return $subtotal;
    }

My primary question is: Should I operate in PHP using float except when doing bcmath operations since that is the equivalent data type in the database or should I generally avoid using float data types except when creating/updating/reading with the database?

The former option would be something more like:

    public function get_payments_total(): float
    {
        $subtotal = 0.0;

        foreach($this->get_payments() as $payments)
        {
            if(!$payments['cash_adjustment'])
            {
                $subtotal = (float)bcadd((string)$payments['payment_amount'], (string)$subtotal);
            }
        }
        return $subtotal;
    }

Option three, I suppose, would be to stop trying to make PHP more strictly typed and just don't assign data types as long as I use bcmath with monetary numbers.

objecttothis
  • 45
  • 1
  • 7
  • Regardless of the database aspect, if it is indeed monetary values, never store or cast into a `float`, only madness that way lies – Uberfuzzy Oct 21 '21 at 13:07
  • Thanks, that's helpful. You might want to post your comment as an answer so that people can upvote it and mark it as the accepted answer. – objecttothis Oct 21 '21 at 13:20

0 Answers0