Video in progress
Which type should you use to store money amounts in the database, and why is `double` a bad idea?
For money use numeric(p, s) (for example numeric(15,2)) or an integer in the smallest unit (bigint in cents). double precision is a binary fraction, so it can't store numbers like 0.1 exactly, and rounding errors add up.
📖 Answer
SELECT 0.1::float8 + 0.2::float8; -- 0.30000000000000004
SELECT 0.1::numeric + 0.2::numeric; -- 0.3
In a single operation the difference is tiny, but over a million transactions the cents "disappear" and the accounting balance doesn't add up.
It's the same on the Java side: numeric maps to BigDecimal, not double.
@Column(precision = 15, scale = 2, nullable = false)
private BigDecimal amount;
Create a BigDecimal with new BigDecimal("0.1") or BigDecimal.valueOf(...), not new BigDecimal(0.1), or the double error sneaks back in. When comparing, use compareTo, not equals: 2.0 and 2.00 are not equal by equals.
The bigint option (in cents) is also good: it's fast and simple, just don't forget to divide by 100 when displaying. The money type in PostgreSQL depends on the locale setting, so it's usually not recommended.
Sign up to mark studied questions and save your progress.