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.
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.
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);
}25.00 USD
currency mismatchWhole 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.