← Tous les articles

PHP money calculations: prices and tax without rounding errors

Why floats break your invoices, and how to handle money as integer cents in PHP: parsing input, tax, splitting amounts and display.

PHP money calculations: prices and tax without rounding errors

Key points

  • Never store or calculate a price as a float: use integer cents.
  • Tax and discounts are computed with integers, using one rounding rule written in one place.
  • Converting back to a decimal amount is for display only, through NumberFormatter.

“The invoice total is off by one cent.” Almost every application that handles money gets that ticket eventually, whether it’s a quoting tool, a shop or a SaaS billing its subscribers. The customer is right, and the cause is nearly always the same: amounts handled as floating-point numbers. Here’s how we structure money code in PHP so the pennies add up.

What’s wrong with floats

A float holds a binary approximation, and most decimal values, like 0.1 or 19.99, can’t be stored exactly:

var_dump(0.1 + 0.2 == 0.3);     // bool(false)
var_dump((int) (19.99 * 100));   // int(1998), not 1999

The second line is the nasty one: a 19.99 price cast to cents becomes 19.98. Tests with round prices never catch it; the first .99 price in production does. Our rule: in the database, money is an integer (INT or BIGINT) in the smallest unit, and it stays an integer throughout the business logic.

Parse input without going through a float

User input is the next trap. In a French or German interface people type 19,99, and (float) '19,99' gives 19 because PHP stops at the comma. If your forms accept both conventions, parse the string yourself. This version treats the comma as a decimal separator, so adapt it if your users type thousands separators with commas:

function to_cents(string $input): int
{
    // "1 234,50" or "1234.5" -> 123450
    $clean = str_replace([' ', "u{00A0}", "u{202F}", ','], ['', '', '', '.'], trim($input));

    if (!preg_match('/^(d+)(?:.(d{1,2}))?$/', $clean, $m)) {
        throw new InvalidArgumentException("Invalid amount : {$input}");
    }

    return (int) $m[1] * 100 + (int) str_pad($m[2] ?? '0', 2, '0');
}

It strips the non-breaking spaces some locales insert and rejects anything else instead of guessing. A clear validation error beats a silently wrong amount.

Tax, discounts and splits with integers

Express percentages in basis points, which also keeps rates like 5.5% away from floats:

// Rate in basis points: 2000 = 20%, 550 = 5.5%
function vat_cents(int $netCents, int $rateBp): int
{
    // Round half up to the nearest cent (positive amounts)
    return intdiv($netCents * $rateBp + 5000, 10000);
}

vat_cents(1999, 2000); // 400 (3.998 rounded to 4.00)

This rounds half up and assumes positive amounts; for credit notes, work on the absolute value and restore the sign. Also decide whether tax is rounded per line or on the total, and match whatever your client’s accounting software does. On our projects that decision, more than the code, is where discrepancies come from.

One more classic: splitting an amount into instalments or across cost centres. Dividing and rounding each share loses or gains a cent, so hand out the remainder instead:

function allocate(int $totalCents, int $parts): array
{
    $base = intdiv($totalCents, $parts);
    $rest = $totalCents % $parts;

    $shares = [];
    for ($i = 0; $i < $parts; $i++) {
        $shares[] = $base + ($i < $rest ? 1 : 0);
    }
    return $shares;
}

allocate(10000, 3); // [3334, 3333, 3333] - adds up to exactly 10000

Display, and only display

Turning cents back into a currency amount happens at render time, with the intl extension:

$fmt = new NumberFormatter('en_GB', NumberFormatter::CURRENCY);
echo $fmt->formatCurrency($cents / 100, 'EUR'); // €1,234.50

Dividing by 100 is safe here because the result never feeds another calculation. With several currencies, store the currency next to the amount: the Japanese yen has no minor unit and some currencies use three decimals. Payment providers such as Stripe already expect amounts in the smallest currency unit, so your data maps straight across.

FAQ

What about bcmath?

It’s handy for rates with many decimals, such as exchange rates or interest. For prices and sales tax, integer cents are enough and easier to read.

My database already uses DECIMAL or FLOAT columns. Now what?

DECIMAL(10,2) is exact in the database; the trouble starts when PHP turns it into a float. FLOAT columns should be migrated to integer cents with explicit rounding, checking totals before and after.

Does your app bill customers and the totals don’t always add up? We audit and harden the pricing logic behind quotes, orders and subscriptions.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →