Why Java Silently Lost 1 Unit in Production

The Silent Subtraction



Silent precision loss never throws an exception. The database holds an exact trade value of 19,574,929. Your backend service executes a standard query to fetch that row. No exception is thrown anywhere along the pipeline. Yet, Java logs the trade value as 19,574,928. One unit vanished without a warning or stack trace. Somewhere between the database socket and your heap, a number mutated.

Database vs Runtime

Open your database console and run the exact same SELECT query. The database returns 19,574,929 every single time. Now execute the repository call inside your Java application. The runtime variable holds 19,574,928.0f instead. Same row, same query, but two completely different numbers. The database never lied; the mutation happened in your application.

SQL CONSOLE

SELECT amount
FROM trades
WHERE id = 42;

-- returns 19574929

JAVA RUNTIME

float amount =
    rs.getFloat("amount");

// amount is 19574928.0f

The Mapping Layer

A single getter coerced the type and lost precision.

public Trade findById(long id) throws SQLException {
    String sql = "SELECT id, amount FROM trades WHERE id = ?";
    try (PreparedStatement ps = conn.prepareStatement(sql)) {
        ps.setLong(1, id);
        try (ResultSet rs = ps.executeQuery()) {
            if (!rs.next()) return null;
            float amount = rs.getFloat("amount");
            return new Trade(rs.getLong("id"), amount);
        }
    }
}

Look at the repository method mapping rows to domain objects. Line 7 retrieves the monetary value from the result set. The code calls ResultSet.getFloat() to read the column. The database column was defined as a precise numeric type. Calling getFloat() forces the JDBC driver to cast it to 32 bits. That single method call quietly destroys your trade value.

The 24-Bit Boundary

Past 2^24, floats cannot represent every integer.

  • Below 2^24: every integer exists 16,777,214, 16,777,215, 16,777,216
  • Above 2^24: gap = 2 → odd integers vanish 19,574,928, 19,574,929 (missing), 19,574,930

A standard IEEE 754 32-bit float has only 24 bits of precision. Below 2^24, every integer has an exact representation. The value 16,777,216 marks the exact boundary of precision. Above that boundary, the distance between adjacent floats jumps to 2. Every odd integer simply vanishes from existence. Your value of 19,574,929 is odd, so it cannot exist.

Rounding to Nearest Even

Write 19,574,929 in binary, and you count 25 significant bits. A 32-bit float keeps only 24 significant bits. The least significant bit falls outside the storage limit. So the value is rounded to the nearest float, and it sits exactly halfway between two. IEEE 754 breaks the tie toward the float whose last mantissa bit is 0: 19,574,928. The value is rounded down before your code ever sees it.

Doubles Fail the Same Way

Doubles only postpone the exact same integer precision cliff.

  • FLOAT LIMIT (2^24) 16,777,216
  • DOUBLE LIMIT (2^53) 9,007,199,254,740,992

Many developers assume switching to double fixes the problem forever. A 64-bit double merely pushes the boundary to 2^53. That boundary is 9,007,199,254,740,992. Past that limit, double skips integers just like float does. Summing floating point numbers repeatedly compounds the error over time. Binary floating point types were designed for physics, not finance.

Precision Lost at the Door

Formatting cannot recover precision that was never saved.

  • Formatting cannot recover precision that is already lost.

Do not try to fix this by tweaking your string formatters. Calling String.format cannot resurrect bits that were never stored. Once getFloat() returns, the original value is gone forever. No Jackson serializer or decimal pattern can reverse the rounding. The bug lives in the data type, not the view layer.

Read Money with BigDecimal

Use BigDecimal for money, Long for discrete counts.

Before

float amount = rs.getFloat("amount");

After

BigDecimal amount =
    rs.getBigDecimal("amount");

The fix is replacing the primitive getter entirely. Call rs.getBigDecimal() to keep arbitrary decimal precision. The JDBC driver delivers the exact value from the database engine. No truncation occurs, and no bits are discarded. If the column stores discrete shares or IDs, use getLong(). Never allow a floating point primitive near monetary columns.

Regression Test

A regression test prevents float reintroduction.

@Test
void preservesTradePrecision() throws SQLException {
    Trade trade = repository.findById(42L);
    BigDecimal expected =
        new BigDecimal("19574929");

    assertThat(trade.getAmount())
        .isEqualByComparingTo(expected);
}

Lock the fix in with an explicit regression test. We query the test trade and assert the exact value. Against the old getFloat() code, this test fails immediately. We use isEqualByComparingTo so scale differences do not cause false alarms. With getBigDecimal() in place, the assertion passes cleanly.

Ban float getters with forbidden-apis

Ban floating point getters across financial repositories.

  • $ ./gradlew forbiddenApisMain
  • Forbidden method invocation: java.sql.ResultSet#getFloat(java.lang.String) [Use getBigDecimal() or getLong()]
  • in com.example.TradeRepository (TradeRepository.java:7)
  • BUILD FAILED

Code reviews alone will not stop this bug from returning. Add the forbidden-apis Gradle plugin with a rule for ResultSet float getters. Any PR calling getFloat() or getDouble() should fail the build. Force your team onto getBigDecimal() and getLong() by default. Stop precision bugs before they ever reach a production cluster.

Remember the Boundary

Never use float for money.

  • Float cannot represent every integer past 16,777,216.
  • Use BigDecimal for money, Long for counts.
  • New production bug tomorrow. Subscribe and steal the fix.

Float loses integer precision the moment you cross 2^24. Double does the exact same thing past 2^53. Store financial decimals in BigDecimal, and discrete counts in Long. Never trust floating point primitives with values that matter.


Watch more on YouTube · follow on Facebook.