user3968645
user3968645

Reputation: 135

Subtract until zero

Okay so let's say I have

A balance of $6.00 created from a credit.

An invoice of $12.00 created by an admin.

You subtract the invoice amount from the balance and get a total of $-6.00

How would you subtract the two until you reach $0.00 to figure out the amount taken from the balance to pay the invoice.

So you would get that the balance paid for was a total of $6.00 and the client still owes $6.00

My PHP code is as follows for this predicament!

if($balance >= $due)
    {
        $amount = $due;
    }
    else
    {
        $amount = $due - $balance;
    }

    if($balance > '0')
    {
        $data = array(
            'invoice_id' => $invoice_id,
            'balance_pay' => '1',
            'amount' => 
        );

        $this->payment->create($data);
    }

UPDATE

I'm just trying to figure out how much is still owed on the invoice. If I don't figure this out, because of how my application is set-up, it will display that the total invoice was paid when really only half of it was paid.

Upvotes: 0

Views: 2459

Answers (1)

wookie919
wookie919

Reputation: 3134

This is a VERY simple problem, that has needlessly been complicated, which often happens. Just need to take a step back rather than getting deeper into the problem (if that is even possible) and further complicatingn the issue.

Firstly, you don't have to subtract to reach $0.00.

In the most general case, the amount of current credit balance could be negative (customer currently owes you money), 0 (customer does not owe you any money currently), or positive (you currently owe customer money). But the actual calculation is the same in all three cases. Let the current credit balance for the customer be x.

Now you wish to generate an invoice. Let this invoice amount be y. (I assume that y will always be positive, but doesn't really matter.)

Then, z = x - y is the new credit balance for the customer:

  • If z < 0: customer did not have enough credit balance to pay off the new invoice. Customer still needs to pay z.
  • If z = 0: customer had just enough credit balance to completely pay off the new invoice, and the new credit balance is 0.
  • If z > 0: customer had more than enough credit to pay off the new invoice, and the new credit balance is z.

It's just straightforward addition/subtraction, needlessly complicated in your head by credit/debit/plus/minus signs, with the added confusion resulting from wanting to balance to zero when you really don't have to.

Upvotes: 2

Related Questions