BBizKit

money.add

v0.1.0 latest

Add two Money values with same-currency and same-scale enforcement per ISO 4217.

moneyarithmeticbigintadditioniso4217

Add two Money values with same-currency and same-scale enforcement per ISO 4217.

Signature

function add(a: Money, b: Money): Money

Type Definitions:

Problem

Adding monetary values requires currency and scale validation. Silently adding USD + EUR or scale=2 + scale=3 produces meaningless results. Number-based addition loses precision for large amounts.

How It Works

Validates that both operands share the same currency and scale, then performs bigint addition for exact arithmetic.

Boundaries

  • Currency mismatch → TypeError (e.g. USD + EUR).
  • Scale mismatch → TypeError (e.g. scale=2 + scale=3).
  • No implicit scale alignment — callers must ensure compatible scales.

Replaces

Common boilerplate this function replaces:

{ amount: a.amount + b.amount, currency: a.currency, scale: a.scale }

Examples

money.add({ amount: 100n, currency: "USD", scale: 2 }, { amount: 200n, currency: "USD", scale: 2 });  // { amount: 300n, currency: "USD", scale: 2 }
money.format(money.add(money.parse("10.00 USD")!, money.parse("5.50 USD")!));  // "15.50 USD"

Standards

Caveats

  • No implicit scale alignment. If you need to add values with different scales, convert them first.
  • Result can exceed safe integer range for Number but is exact as bigint.

FAQ

How to add money values safely in JavaScript?

money.add(a, b) performs exact bigint addition after validating same currency and scale.

What happens when currencies don't match?

TypeError is thrown. You must convert currencies explicitly before adding.

What happens when scales don't match?

TypeError is thrown. Convert to the same scale before adding.

Can money.add handle very large amounts?

Yes. BigInt has arbitrary precision — no overflow at Number.MAX_SAFE_INTEGER.

How to add money with different decimal places?

Align scales first by multiplying/dividing the amount, then add.

Referenced Standards