今日已更新 412 条资讯 | 累计 19972 条内容
关于我们

Modeling Money in PHP: Your Own Value Object vs brick/money Behind a Port

Gabriel Anhaia 2026年06月14日 05:39 3 次阅读 来源:Dev.to

Book: Decoupled PHP — Clean and Hexagonal Architecture for Applications That Outlive the Framework Also by me: Thinking in Go (2-book series) — Complete Guide to Go Programming + Hexagonal Architecture in Go My project: Hermes IDE | GitHub — an IDE for developers who ship with Claude Code and other AI coding tools Me: xgabriel.com | GitHub Open a PHP REPL and type 0.1 + 0.2 . You get 0.30000000000000004 . Now imagine that drift sitting in a total column on an invoice. The bug report does not say "IEEE 754 rounding." It says "the customer was charged one cent too much and finance wants to know why." Money is not a number. It is an amount paired with a currency, and it follows rules a float does not know about. You cannot add 10 USD to 10 EUR. You cannot store 19.99 in a binary fraction and expect it back. You cannot round a third of a cent without deciding how to round it, and that decision belongs to your business, not to your storage engine. This post builds a small Money value object that gets the currency safety right, then shows when to stop hand-rolling and wrap brick/money behind a domain port instead. The point of the port is the same point as every port: the rounding rules live in your domain, and the library stays swappable. Why a float is the wrong type Three separate problems hide inside float $amount . The first is representation. A float is a binary fraction. Decimal amounts like 0.10 have no exact binary form, so they round on every store and load. Sum a few thousand line items and the error compounds into real cents. The second is the missing currency. A bare number cannot tell you whether 1000 means ten dollars or one thousand yen. Two amounts in different currencies are not comparable, but the type system lets you add them anyway. The third is the rounding rule. When you split 10.00 across three line items, you get 3.333... per item. Someone has to decide who absorbs the leftover cent. A float makes that decision silently and inconsistently. The fix

本文内容来源于互联网,版权归原作者所有
查看原文