Return to site

💰🔢 AVOID FLOAT & DOUBLE WHEN YOU NEED EXACT ANSWERS

· java,programmmer
Section image

🔸 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👇