money.sub
v0.1.0 latestSubtract two Money values with same-currency and same-scale enforcement per ISO 4217.
Subtract two Money values with same-currency and same-scale enforcement per ISO 4217.
Signature
function sub(a: Money, b: Money): Money
Type Definitions:
Money— interface
Problem
Subtracting monetary values requires the same currency and scale validation as addition. Result can be negative (e.g. refund exceeding balance), which must be represented correctly.
How It Works
Validates same currency and scale, then performs bigint subtraction. Result can be negative.
Boundaries
- Currency mismatch → TypeError.
- Scale mismatch → TypeError.
- Result can be negative (e.g. sub(5.00, 10.00) → -5.00).
Replaces
Common boilerplate this function replaces:
{ amount: a.amount - b.amount, currency: a.currency, scale: a.scale }
Examples
money.sub({ amount: 300n, currency: "USD", scale: 2 }, { amount: 100n, currency: "USD", scale: 2 }); // { amount: 200n, currency: "USD", scale: 2 }
money.format(money.sub(money.parse("10.00 USD")!, money.parse("3.25 USD")!)); // "6.75 USD"
Standards
Caveats
- Result can be negative — represents debits, refunds, or overdrafts.
- Same scale enforcement as money.add — no implicit alignment.
FAQ
How to subtract money values in JavaScript?
money.sub(a, b) performs exact bigint subtraction after validating same currency and scale.
Can money.sub return negative values?
Yes. money.sub({ amount: 100n, ... }, { amount: 300n, ... }) returns { amount: -200n, ... }.
What validation does money.sub perform?
Same as money.add: currency mismatch or scale mismatch throws TypeError.
How to check if a subtraction result is negative?
Check result.amount < 0n after subtraction.
Is money.sub exact?
Yes. BigInt subtraction is exact — no floating-point precision issues.