In PHP Is it better to leave the result of bcmath functions as strings or cast the result back to a float?

251 views Asked by At

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.

0

There are 0 answers