Currency Amounts API
CartThrob 10.0.1 adds CartThrob\Money\CurrencyAmount, a small static class that add-ons can use for exact money handling: normalizing ISO currency codes, resolving a currency’s decimal precision, and converting between decimal strings and integer minor units (cents, pence, fils) without passing a value through a float.
Use it whenever your add-on stores, sums, compares or re-charges amounts outside of a live cart. Totals that go through the cart are already handled by CartThrob; this API is for the arithmetic you do yourself, such as renewals, refunds, instalments, credits and reconciliation.
CartThrob’s own checkout keeps using CartThrob\PaymentGateways\PaymentAmountValidator. Its behaviour is unchanged in 10.0.1; its precisionForCurrency() now reads the same ISO table as the class below.
Why minor units
Floating-point money drifts: 0.1 + 0.2 is not 0.3, and 0.29 * 100 is 28.999999999999996. Zero-decimal currencies (JPY), three-decimal currencies (KWD, BHD) and four-decimal ones (CLF) make the usual “multiply by 100” wrong as well. Working in integer minor units with the currency’s real precision avoids both problems, and it is what payment providers expect.
The class
All methods are static. The class has no ExpressionEngine or database dependencies, so it is safe to call from CLI commands, cron and tests.
use CartThrob\Money\CurrencyAmount;
CurrencyAmount::normalizeCode(' usd '); // 'USD'
CurrencyAmount::normalizeCode('us'); // ''
CurrencyAmount::precision('JPY'); // 0
CurrencyAmount::precision('USD'); // 2
CurrencyAmount::precision('KWD'); // 3
CurrencyAmount::precision('CLF'); // 4
CurrencyAmount::precision('XYZ', 2); // 2, the fallback for unknown codes
CurrencyAmount::toMinorUnits('12.50', 2); // 1250
CurrencyAmount::toMinorUnits('12.5', 2); // 1250
CurrencyAmount::toMinorUnits('12.500', 2); // 1250, trailing zeros are not excess digits
CurrencyAmount::toMinorUnits('12.505', 2); // null, too many fractional digits in strict mode
CurrencyAmount::toMinorUnits('12.505', 2, true); // 1251, rounded half away from zero
CurrencyAmount::toMinorUnits('-4.20', 2); // -420, signed values for refunds and adjustments
CurrencyAmount::toMinorUnits('1500', 0); // 1500
CurrencyAmount::toMinorUnits('abc', 2); // null
CurrencyAmount::fromMinorUnits(1250, 2); // '12.50'
CurrencyAmount::fromMinorUnits(-420, 2); // '-4.20'
CurrencyAmount::fromMinorUnits(5, 3); // '0.005'
CurrencyAmount::fromMinorUnits(1500, 0); // '1500'
normalizeCode($code): string
Returns the upper-cased, trimmed three-letter code, or an empty string for anything that is not one. Non-strings return an empty string.
precision($code, int $fallback = 2): int
Returns the ISO 4217 subunit count for the code. A blank, unknown or malformed code returns the fallback, which is clamped to zero or more. Store the fallback you want rather than relying on the default when the store currency can be configured.
toMinorUnits($amount, int $precision, bool $round = false): ?int
Parses a decimal string with integer arithmetic only. Accepts an optional leading minus sign, digits, and an optional decimal point followed by digits; surrounding whitespace is ignored, and ints and floats are cast to string first. Returns null for anything else, for magnitudes above PHP_INT_MAX, and, in strict mode, for more significant fractional digits than the precision allows. With $round true, excess digits round half away from zero. Decide which mode you want per input: strict for values a customer or administrator typed, rounded for values you computed.
fromMinorUnits(int $minor, int $precision): string
Returns the normalized decimal string with exactly $precision fractional digits and a leading minus sign for negatives. This is the form to store, display and send to a gateway that takes decimal amounts.
Pattern: snapshot the currency, then work in integers
The class only does arithmetic. Which currency a record uses, and what to do when it is unknown, is your add-on’s decision. The pattern CartThrob Subscriptions 6 follows:
- When the record is created, store the currency code and its precision alongside it. Subscriptions keeps
currency_codeandcurrency_precisionon each Subscription, taken from the Order that created it. - Read every stored amount into minor units with
toMinorUnits()in strict mode at that precision. Anullmeans bad data; stop and report it rather than guessing. - Add, multiply and compare the integers.
- Format results back with
fromMinorUnits()at the same precision before storing, displaying or charging.
use CartThrob\Money\CurrencyAmount;
$code = CurrencyAmount::normalizeCode($subscription->currency_code) ?: $storeCurrency;
$precision = (int)$subscription->currency_precision;
$price = CurrencyAmount::toMinorUnits($subscription->price, $precision);
$tax = CurrencyAmount::toMinorUnits($calculatedTax, $precision, true);
if ($price === null || $tax === null) {
throw new RuntimeException('Subscription amounts are not valid for ' . $code);
}
$total = $price + $tax;
$chargeAmount = CurrencyAmount::fromMinorUnits($total, $precision); // e.g. '14.52'
Subscriptions wraps these calls in its own SubscriptionCurrency service, which adds the policy the class leaves out: the store default when a legacy record has no currency, recovery of the code from the original Order, persistence of the snapshot, and a rule that stored amounts are never negative. Your add-on will want an equivalent thin wrapper; keep the policy there and the arithmetic here.
What this is not
- It does not convert between currencies.
- It does not read the store currency or any setting; pass codes in.
- It does not validate a payment against a gateway response. That stays with
PaymentAmountValidator::matches()in checkout.