๐ธ TLDR
- When you deal with money ๐ถ, counters ๐, IDs ๐, or anything that must be 100% accurate, do NOT use float / double.
- They are binary floating-point types โ they approximate.
- Use BigDecimal (Java), integers representing smallest unit (cents), or fixed-point types instead. โ
๐ธ WHY FLOAT/DOUBLE CAN'T BE TRUSTED IN FINANCE
- float and double store decimal values in binary form.
- Some decimal numbers canโt be represented exactly in binary โ tiny rounding errors.
- Those "tiny" errors become huge when you sum, multiply taxes, apply discounts, etc. ๐ฌ
Java example ๐
System.out.println(0.1 + 0.2);
// 0.30000000000000004 ๐ฑ
Imagine that in an invoice at scale. 1 cent off per transaction ร 1M transactions = real money.
๐ธ WHAT TO USE INSTEAD ๐ก
๐ธ MONEY / PRICES
โช๏ธ Use BigDecimal
BigDecimal price = new BigDecimal("19.99");
BigDecimal tax = new BigDecimal("0.20");
BigDecimal total = price.multiply(tax).add(price);
System.out.println(total); // exact โ
โช๏ธ Or store cents as long
long priceInCents = 1999; // 19.99โฌ
long taxInCents = priceInCents * 20 / 100;
long totalInCents = priceInCents + taxInCents;
Then only format to euros at display time.
๐ธ COUNTERS / QUANTITIES / IDs
โช๏ธ Use int, long, BigInteger for counts and IDs.
Example: stock of items in a warehouse should never be a double.
There is no such thing as 12.499 sneakers in stock ๐.
๐ธ WHEN FLOAT/DOUBLE ARE OK ๐
โช๏ธ Physics, graphics, geometry, measurements, analytics dashboards.
If you're modeling the real world (which is already approximate), double is fine.
Example: GPS coordinates, temperature, CPU usage %, etc. ๐ก๏ธ๐ฐ๏ธ
Those values are inherently "close enough", not "financially auditable".
๐ธ TAKEAWAYS ๐
โช๏ธ float / double lie a little.
โช๏ธ Money canโt tolerate lies.
โช๏ธ Use BigDecimal (or integer cents) for prices, taxes, invoices.
โช๏ธ Use integer types for counters and quantities.
โช๏ธ Keep double for science/math/graphics, not for billing.
#cleanCode #java #programmingTips #BigDecimal #softwareengineering #bugprevention #backend #money #precision
Go further with Java certification:
Java๐
Spring๐
SpringBook๐