Scrivio Interview library
DebuggingFoundations6 min read · updated 12 November 2026

A Java service stores prices as double and a PostgreSQL column as real. Customers see totals like 19.989999. What is wrong and how should money be modelled in Java and SQL?

double in Java and real in PostgreSQL are binary floating-point types, which cannot represent most decimal fractions such as 19.99 exactly, so values read back as 19.989999 and sums drift. Money should be NUMERIC(19,4) in SQL, or a bigint of minor units such as cents, always with a currency code, and BigDecimal with an explicit scale and RoundingMode in Java, or long minor units or a money library like Moneta.

Why this question is asked

Few bugs make customers lose trust as fast as a wrong price. A total of 19.989999 on an invoice tells them that our system cannot count. Interviewers ask this because the root cause is a basic fact about how computers store numbers, and the fix touches the database, the Java code and the rounding rules. In this answer, we will see why floating point cannot hold 19.99, reproduce the bug, fix the SQL column and the Java types, look at the BigDecimal traps, and decide where rounding happens.

1Why Floating Point Cannot Store 19.99

double and float store numbers in binary, as a fraction whose denominator is a power of two. Some decimals fit exactly, such as 0.5 or 0.25. But 0.1, 0.2 and 0.99 have no exact binary form, just as one third has no exact decimal form. The computer stores the nearest binary value it can, which is very slightly off.

real in PostgreSQL is a 4-byte float with about 6 to 7 significant decimal digits, and double precision is 8 bytes with about 15 to 16. The service in the question has the worse of both: the database keeps prices as 4-byte floats, and Java widens them to double, which exposes the error.

Java
float stored = 19.99f; // what a real column holds
double shown = stored; // 19.989999771118164: the error becomes visible
System.out.println(0.1 + 0.2); // 0.30000000000000004
double total = 0;
for (int i = 0; i < 10; i++) total += 0.1;
System.out.println(total); // 0.9999999999999999, not 1.0

Notice that each single error is tiny, but it never cancels out reliably. Additions and multiplications by quantities and tax rates keep the error, and rounding a drifted 2.675 can go the wrong way. Money needs exact decimal arithmetic.

2Fixing the SQL Column

PostgreSQL's NUMERIC, also called DECIMAL, stores decimal digits exactly. NUMERIC(19,4) means up to 19 digits in total with 4 after the point, which is enough for very large amounts and for currencies or intermediate prices that need more than two decimals. The alternative is to store the amount in minor units, such as cents, in a bigint: 1999 means 19.99 in a currency with two decimals. Either way, an amount without a currency is not money, so the currency code from ISO 4217 sits next to it.

SQL
ALTER TABLE order_line
ALTER COLUMN unit_price TYPE numeric(19,4) USING round(unit_price::numeric, 2),
ADD COLUMN currency char(3) NOT NULL DEFAULT 'EUR';
SELECT 0.1::real + 0.2::real; -- 0.3 shown, but not exact internally
SELECT 0.1::numeric + 0.2::numeric; -- 0.3 exactly
SELECT sum(unit_price) FROM order_line; -- exact decimal sum

The USING clause rounds the old floats to two decimals during the conversion, which repairs values like 19.989999. We should check that rounding against source data such as the price list, because some values may already have drifted further. PostgreSQL also has a money type, but it depends on a locale setting and carries no currency, so it is best avoided.

3Fixing the Java Types

In Java, BigDecimal represents a decimal exactly, as an unscaled integer plus a scale, the number of digits after the point. Every division and every rounding step must say how to round, with a RoundingMode. HALF_EVEN, often called banker's rounding, rounds halves to the nearest even digit, which avoids a systematic upward bias across many sums; finance decides which mode applies.

Java
BigDecimal price = new BigDecimal("19.99");
BigDecimal qty = BigDecimal.valueOf(3);
BigDecimal net = price.multiply(qty); // 59.97
BigDecimal vat = net.multiply(new BigDecimal("0.19"))
.setScale(2, RoundingMode.HALF_EVEN); // 11.39 (from 11.3943)
BigDecimal gross = net.add(vat); // 71.36
// JPA mapping
@Column(precision = 19, scale = 4)
private BigDecimal unitPrice;
@Column(length = 3)
private String currency;

Two alternatives are also sound. We can carry long minor units (1999 cents) in Java, which is fast and simple but makes us handle currencies with zero or three decimals carefully. Or we can use JSR 354, the Java Money API, through its reference implementation Moneta, where Money.of(new BigDecimal("19.99"), "EUR") keeps amount and currency together and refuses to add euros to dollars.

4The Two BigDecimal Traps

The first trap is building a BigDecimal from a double. The constructor takes the double's exact binary value, error included. BigDecimal.valueOf uses the double's shortest string form instead, and a string constructor is exact.

Java
new BigDecimal(0.1); // 0.1000000000000000055511151231257827021181583404541015625
BigDecimal.valueOf(0.1); // 0.1
new BigDecimal("0.1"); // 0.1
BigDecimal a = new BigDecimal("2.0");
BigDecimal b = new BigDecimal("2.00");
a.equals(b); // false: equals compares value and scale
a.compareTo(b) == 0; // true: compareTo compares numeric value only
Set.of(a).contains(b); // false, for the same reason
Step throughCorrect path of a price through the system
  1. Price list or APIstring or decimal, never double
  2. BigDecimal in Javanew BigDecimal("19.99") or valueOf
  3. Calculationsfull precision, explicit scale on division
  4. Round once per rulefor example per line, HALF_EVEN
  5. NUMERIC(19,4) plus currencyexact storage
  6. Displayformatted for the currency's decimals

6 steps in order. Play them, or step through them one at a time.

The second trap is equals. BigDecimal.equals considers 2.0 and 2.00 different because their scales differ. So we compare amounts with compareTo, and before using amounts as keys in a HashMap or HashSet, we normalise them with stripTrailingZeros() or a fixed setScale.

5Follow-up questions

Where in the flow should rounding happen?

At the points the business rules name, and nowhere else. We keep full precision during intermediate calculations, such as unit price times quantity and discount percentages, and round when a value becomes an official amount: usually each invoice line or tax amount, as the tax rules of the country require. Rounding too early, for example after each discount step, adds errors; rounding too late can make line totals not add up to the invoice total. Finance should document which rule applies, and the code should round in one clearly named place.

Is long in cents always better than BigDecimal?

It is faster and has no scale confusion, but it is easy to forget which currencies have zero decimals (JPY) or three (KWD), and percentages still need decimal maths. Many systems store minor units in the database and use BigDecimal or a money type in the domain code.

Can JSON lose precision too?

Yes. JSON numbers are often parsed as doubles by JavaScript and many libraries. Sending amounts as strings, or as integer minor units with a currency, avoids that.

6Conclusion

In this answer, we saw that binary floating point cannot represent most decimal fractions, so a real column read into a double shows 19.989999 and sums drift. Money belongs in NUMERIC(19,4) or a bigint of minor units, with a currency code, and in Java in BigDecimal with explicit scale and RoundingMode, long minor units or Moneta. We never build BigDecimal from a double, we compare with compareTo rather than equals, and we round only at the points the business rules define.

What to say in the interviewAbout 80 seconds aloud

Open with

The problem is that double in Java and real in PostgreSQL are binary floating-point types. They cannot represent most decimal fractions exactly, so 19.99 is stored as the nearest binary value.

Then, if they want more

A real only has about seven significant digits, and when Java widens it to a double we see 19.989999771, and sums of such values drift. For money I would change the column to NUMERIC(19,4), or store the amount in minor units as a bigint, and add a currency code column, because an amount without a currency is not money.

The migration can round the old values, but I would check them against the source data. In Java I would use BigDecimal with an explicit scale and RoundingMode, for example HALF_EVEN if finance agrees, or long minor units, or a money library like Moneta that keeps amount and currency together.

Two traps: never write new BigDecimal(0.1), since that captures the binary error; use BigDecimal.valueOf or the string constructor. And compare amounts with compareTo, because equals treats 2.0 and 2.00 as different. Rounding should happen once, at the points the business rules define, such as each line or tax amount.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A Java service stores prices as double and a PostgreSQL column as real. Customers see...": https://scrivio-interview-library.netlify.app/databases/data-modeling/7f93892d85/