DEV Community

Murabyte
Murabyte

Posted on

Why invoice amounts should be stored as integer cents (PHP example)

Disclosure: I make WaInvoice at Murabyte, which is mentioned at the end.

Open a JavaScript or PHP console and add 0.1 and 0.2. You do not get 0.3 exactly. In an invoice, that kind of drift shows up as a total that is one cent off. The usual fix is to store money as whole cents.

The problem

$total = 0.1 + 0.2;
var_dump($total == 0.3);   // bool(false)
Enter fullscreen mode Exit fullscreen mode

Binary floating point cannot store most decimal fractions exactly. With many line items, tax and discounts, rounding errors add up.

Store integer cents

function toCents(string $s): int {
    if (!preg_match('/^\d+(\.\d{1,2})?$/', $s)) {
        throw new InvalidArgumentException('Invalid amount');
    }
    return (int) round(((float)$s) * 100);
}

$unit  = toCents('19.99');   // 1999
$qty   = 3;
$line  = $unit * $qty;       // 5997
Enter fullscreen mode Exit fullscreen mode

Use an integer column in the database (BIGINT) for the amounts. Format only for display: number_format($cents / 100, 2).

Discounts and tax

Decide the rounding rule once and apply it per line:

$discount = intdiv($line * $discountPercent, 100);   // whole cents
$taxable  = $line - $discount;
$tax      = (int) round($taxable * $taxPercent / 100);
$total    = $taxable + $tax;
Enter fullscreen mode Exit fullscreen mode

Whatever rule you pick, apply it the same way on screen, in the PDF and in the export.

Validate hard

Refuse bad input (letters, negative quantities, 3 decimals) and show an error, instead of saving something silently wrong. Also check the maximum: a very large total can overflow your column type.

Never reuse invoice numbers

Allocate the next number inside a transaction with a lock, and keep the number even if the invoice is deleted. Gaps in numbering are easier to explain than duplicates.

A ready-made version

WaInvoice is a self-hosted PHP/MySQL invoicing app I make at Murabyte for Arabic and English speaking freelancers and small businesses: invoices, quotes and receipts with separate sequential numbers, totals computed in integer cents with strict validation, a public link per document, and a one-tap WhatsApp share that you send yourself. Statuses are manual labels, the admin panel is in English, and hosting is not included. Regular license $24: https://murabyte.gumroad.com/l/wainvoice-arabic-english-invoicing

php #mysql #invoicing #webdev #murabyte

Written with AI assistance and reviewed by Murabyte.

Top comments (0)