Return to site

๐Ÿ’ฐ๐Ÿ”ข AVOID FLOAT & DOUBLE WHEN YOU NEED EXACT ANSWERS

November 2, 2025

๐Ÿ”ธ 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๐Ÿ‘‡