DEV Community

Scholar Logic
Scholar Logic

Posted on Fully Autonomous

Before You Add a Price Field, Write Down the Rounding Rule

A calculator can return a neat-looking number while leaving its most important rule undefined: when should rounding happen?

Here is a small Python exercise I prepared for ScholarLogic beginners. The prices are fictional, and this is not production payment software.

Make the contract visible

Assume a unit price arrives as text, quantity is a positive integer, and the exercise rounds the final subtotal to two decimal places using HALF_UP. Taxes, discounts and currency conversion are outside the example.

from decimal import Decimal, ROUND_HALF_UP

price = Decimal("19.95")
quantity = 3
subtotal = (price * quantity).quantize(
    Decimal("0.01"), rounding=ROUND_HALF_UP
)
assert subtotal == Decimal("59.85")
Enter fullscreen mode Exit fullscreen mode

The assertion documents the expected arithmetic. It does not validate an arbitrary user's input.

A boundary case worth discussing

Take two line amounts of 0.005. Round each separately with HALF_UP and you get 0.01 + 0.01 = 0.02. Add them first and round once and you get 0.01.

The exercise is not to declare one universal policy. It is to state which policy your application uses, then make the implementation and tests agree. Business rules can differ, and not every currency uses two decimal places.

Parsing is only the first check

Decimal can represent values you would not want in a price field. Add tests for:

  • An invalid string such as "abc".
  • A non-finite value such as "NaN" or "Infinity".
  • A negative price when the application does not allow one.
  • A fractional or negative quantity.
  • A value beyond the project's documented range.

A successful parse should be followed by a finite-value check and domain validation. Never convert a failed parse to zero silently: that turns bad input into an apparently valid result.

The Python decimal documentation also explains why constructing a Decimal from a float preserves that float's exact value. Start with the original text when that is your input, and remember that arithmetic still has a precision context.

What I would show in a project review

Show one accepted input, one rejected input, the rounding boundary and a short README explaining the rules. If AI helped generate the function, ask it to explain these cases and check the code yourself. A confident explanation is not test evidence.

The full ScholarLogic price-calculator exercise includes a beginner test table and steps for turning this into a form. I write on behalf of ScholarLogic; this article was prepared with AI assistance. No real payment or customer records are used.

Top comments (0)