Skip to content
jshacks.dev
Patterns

Extract a value object for money

Extract a value object for money in JavaScript: an immutable class that stores integer cents and adds only the same currency. Node.js 24.

1 min read
Summarize in AI

A price stored as a bare number loses its currency and invites float errors. A small value object keeps the amount in integer cents and refuses to mix currencies.

JavaScript
class Money {
  constructor(cents, currency) {
    this.cents = cents;
    this.currency = currency;
    Object.freeze(this);
  }

  add(other) {
    if (other.currency !== this.currency) throw new Error('currency mismatch');
    return new Money(this.cents + other.cents, this.currency);
  }

  toString() {
    return `${(this.cents / 100).toFixed(2)} ${this.currency}`;
  }
}

const total = new Money(1999, 'USD').add(new Money(501, 'USD'));
console.log(String(total));
try {
  total.add(new Money(100, 'EUR'));
} catch (error) {
  console.log(error.message);
}
Text
25.00 USD
currency mismatch

Whole cents avoid the 0.1 + 0.2 problem, and Object.freeze makes each instance immutable, so add returns a new Money. Passing a bare number where a Money is expected now fails on other.currency.

Currencies with no minor unit or three decimals, such as JPY or KWD, need a per-currency scale before toFixed(2) is right. [Intl.NumberFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) knows the digits for each.

Taggednode 24
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.