Scrivio Interview library
DesignAdvanced7 min read · updated 12 November 2026

Many services parse numbers from HTTP parameters, CSV files, message payloads and configuration with different rules, causing incidents with locales, overflow and silent truncation. Propose a standard approach for numeric input handling across the platform.

I would define one canonical wire format for numbers, with a dot as decimal separator, no grouping, documented ranges, and strings for values that do not fit safely in a JSON number, then parse at every boundary into strong value types such as Money, Quantity and Percentage, validated with Bean Validation. Locale-dependent parsing without an explicit locale and float or double for money would be banned by static analysis, overflow handled explicitly with long, BigDecimal and the exact conversion methods, and all of it delivered as a shared library with shared test vectors so every team gets the same behaviour.

Why this question is asked

When dozens of services each parse numbers their own way, the incidents look unrelated: a price read a thousand times too small in one service, a quantity that wrapped negative in another, a percentage truncated to zero in a third. They all come from the same gap, the lack of a platform rule for turning text into numbers. Interviewers ask this design question at a senior level because the answer is not one clever method but a set of standards, types, tools and tests that make the right behaviour the easy one. In this answer, we will recap the common failure modes, define the wire format, design boundary parsing into value objects, decide what to ban and how to enforce it, and plan how to roll it out.

1A Quick Recap of How Numeric Input Goes Wrong

Almost every numeric incident falls into one of four families. Locale problems happen when the parser uses the JVM default locale, so a comma or dot changes meaning between hosts. Overflow happens when a value is parsed or computed in a type too small for it, such as an int for byte counts or a long for unsigned ids, and wraps silently. Silent truncation happens when a parser stops at the first bad character and returns what it has, as NumberFormat.parse(String) does, or when a cast like (int) 2.9 drops the fraction. Precision loss happens when decimal amounts are stored in float or double, or when large integers pass through JavaScript.

The standard has to close each family. Notice that none of them is caused by a lack of parsing methods; Java has plenty. They are caused by choosing a method with the wrong contract in the wrong place.

Failure families and the rule that closes each
FailureTypical causePlatform rule
Locale mismatchNumberFormat.getInstance() without localecanonical format; explicit locale only for files
OverflowparseInt or int math for large valuesparse wide, convert with toIntExact
Silent truncationparse(String) stops early; castsfull-match parsing; exact conversions
Precision lossdouble for money; big ids in JSON numbersBigDecimal; strings for large values
Inconsistent ruleseach team writes its own parsershared library and test vectors

2Defining a Canonical Wire Format

The first decision is what numbers look like whenever two of our systems talk. I would write it as a short standard. JSON numbers are allowed for integers within plus or minus 2^53 - 1 and for measurements where a double is acceptable. Money, ids and any integer that may exceed 2^53 travel as JSON strings containing a plain decimal number. Decimal text always uses a dot as separator, no grouping, an optional leading minus, and no exponent for money. Every field documents its range and scale in the OpenAPI schema or the message schema.

The same canonical format applies to configuration and to message headers. Human-facing formats, such as a German supplier's CSV, are converted at the edge by an adapter that knows that supplier's locale, and from there on only the canonical form exists. So locale handling lives in a few adapters instead of every service.

3Parsing at the Boundary Into Strong Types

Inside a service, numbers should not travel as bare strings, doubles or longs whose meaning is a comment. We parse once, at the boundary, into value objects: small immutable types such as Money, Quantity or Percentage that validate themselves on creation. A record makes this cheap.

Java
public record Money(BigDecimal amount, Currency currency) {
public Money {
Objects.requireNonNull(amount); Objects.requireNonNull(currency);
if (amount.scale() > currency.getDefaultFractionDigits())
throw new IllegalArgumentException("too many decimals: " + amount);
}
public static Money parse(String text, Currency currency) {
return new Money(new BigDecimal(text.strip()), currency); // strict: "1,234.50" throws
}
}
public record CreateOrder(
@NotNull @Digits(integer = 10, fraction = 2) @DecimalMin("0.00") BigDecimal price,
@Min(1) @Max(10_000) int quantity) {}
Money.parse("19.99", Currency.getInstance("EUR")); // Money[amount=19.99, currency=EUR]
Money.parse("19.999", Currency.getInstance("EUR")); // IllegalArgumentException: too many decimals
Step throughWhere numeric input is handled
  1. Edge adapterssupplier CSV, partner feeds: explicit locale, convert to canonical
  2. Transportcanonical format: dot decimal, strings for big values
  3. Boundary DTOsBean Validation: @Digits, @Min, @Max
  4. Value objectsMoney, Quantity, Percentage validate on creation
  5. Domain codeworks only with typed values, never raw text

5 layers, from the top down. Step through them one at a time.

Each layer has one numeric responsibility, so rules are not repeated or forgotten.

Notice the division of work. Bean Validation annotations such as @Digits, @Min, @Max and @DecimalMin check request DTOs declaratively, so Spring returns a clear 400 response with the field name before our code runs. The value object enforces the rules that must hold everywhere, even when the value is created from a message or a database row. After the boundary, code receives a Money, not a string, and cannot forget to validate it.

new BigDecimal(text) is a good strict parser for the canonical format: it rejects grouping and locale characters and keeps the exact digits. Where an adapter must read a locale format, it uses the full-match technique with ParsePosition so trailing text is an error rather than ignored.

4Handling Overflow Explicitly

The rule for integers is to parse wide and narrow on purpose. We parse into long, or BigDecimal and BigInteger where the range is open, and convert to smaller types with methods that throw instead of wrapping: Math.toIntExact, BigDecimal.intValueExact and longValueExact, and Math.addExact and multiplyExact for arithmetic on values from outside.

Java
long raw = Long.parseLong("3000000000"); // 3000000000
int bad = (int) raw; // -1294967296: silent wrap
int good = Math.toIntExact(raw); // ArithmeticException: integer overflow
new BigDecimal("12.7").intValue(); // 12: fraction silently dropped
new BigDecimal("12.7").intValueExact(); // ArithmeticException: Rounding necessary

The exact methods turn a silent data error into an exception at the place the bad value entered, where it is cheap to report. That is the general pattern of the whole standard: fail early and loudly at the boundary, never guess and continue.

5Bans, Static Analysis and Shared Test Vectors

Standards that live only in a document decay. So we enforce the bans with tools. NumberFormat.getInstance() and String.format without a Locale argument, and double or float fields named like price, amount or total, are flagged by static analysis: Error Prone or Sonar rules where they exist, and ArchUnit tests or custom checks for our own conventions, such as forbidding Double.parseDouble in packages that handle money. Check your tool versions for exact rule names. Violations fail the build for new code, while old code gets a baseline and is fixed as teams touch it.

The shared library holds the value objects, the strict parsers and the edge adapters. With it we publish a file of test vectors: inputs and expected results, including 1,234.50, 12,5, trailing junk, empty strings, minus zero, 2^31, 2^53 + 1, 2^63 and over-scaled amounts. Each team runs the same vectors against its own endpoints in a contract test. When a new incident teaches us a new edge case, it goes into the vector file once and every team's build checks it.

Finally, we roll it out gradually: new services adopt it from day one, existing services adopt it at their boundaries first, because that is where incidents start, and a small platform group owns the library and the standard.

6Follow-up questions

Isn't a value object for every number over-engineering?

Not for numbers with business meaning and rules, such as money, quantities and percentages; they cause the incidents, and the type documents the rules at no runtime cost worth mentioning. Plain counters and indexes inside a method can stay ints. The line is whether the value crosses a boundary and carries units or limits.

How do you handle existing APIs that send money as JSON numbers?

We keep accepting them for compatibility, but bind them directly to BigDecimal, which Jackson can do without passing through double when configured to use BigDecimal for floats, and we add the string form as the documented format for new versions. Consumers migrate on the API's normal deprecation schedule.

What about performance of BigDecimal?

BigDecimal is slower than long arithmetic, but numeric parsing at a boundary is rarely the bottleneck compared with I/O. Where it is, for example in high-volume pricing, money can be held as a long count of minor units inside the Money type, keeping the exactness without BigDecimal, as long as overflow is checked.

7Conclusion

In this answer, we designed a platform standard for numeric input. We defined a canonical wire format with dot decimals, no grouping, documented ranges and strings for large values; parsed once at the boundary into value objects such as Money and Quantity, with Bean Validation on DTOs; banned implicit locales and double for money with static analysis; handled overflow by parsing wide and narrowing with exact conversions; and delivered it all as a shared library with shared test vectors, rolled out boundary first.

What to say in the interviewAbout 90 seconds aloud

Open with

I would treat this as a platform standard rather than a set of fixes, because the incidents all come from teams picking parsing methods with different contracts. First, a canonical wire format: plain decimal text with a dot, no grouping, a documented range and scale per field, and any money, id or integer that might exceed 2 to the 53 sent as a JSON string, so JavaScript and other consumers do not lose precision.

Then, if they want more

Locale formats only exist in edge adapters for things like supplier CSV files, each with an explicit locale.

Second, parse once at the boundary into strong types: value objects like Money, Quantity and Percentage that validate themselves, and Bean Validation on request DTOs with @Digits, @Min and @Max, so bad input gets a clear 400 and domain code never sees raw text.

Third, explicit overflow handling: parse into long or BigDecimal and narrow with Math.toIntExact or intValueExact, which throw instead of wrapping. Fourth, bans enforced by tools, not reviewers: no NumberFormat or String.format without a locale and no float or double for money, through Sonar or Error Prone rules and ArchUnit tests, with a baseline for old code.

And finally a shared library plus a shared file of test vectors, with all the nasty cases like 12,5, trailing junk, 2 to the 63, that every team runs in contract tests, so a lesson learned once protects everyone.

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 "Many services parse numbers from HTTP parameters, CSV files, message payloads and...": https://scrivio-interview-library.netlify.app/java/types-and-values/2062e3e431/