DEV Community

SIGNUM HQ
SIGNUM HQ

Posted on AI-assisted

Validate a ratio before formatting it as a percentage

Disclosure: AI was used to draft this standalone example. It is an input-validation exercise, not a description of code deployed in SIGNUM HQ.

A formatting function can make an invalid input look authoritative. For a ratio that represents a subset of a whole, validating the denominator and coverage should happen before producing a percentage. Missing, non-finite and out-of-range inputs deserve separate outcomes.

from decimal import Decimal, InvalidOperation

def subset_percent(part, whole):
    if part is None or whole is None:
        return None, "missing"
    try:
        p, w = Decimal(part), Decimal(whole)
    except (InvalidOperation, TypeError, ValueError):
        return None, "invalid"
    if not p.is_finite() or not w.is_finite():
        return None, "nonfinite"
    if w <= 0 or p < 0 or p > w:
        return None, "invalid_scope"
    return p / w * 100, "ok"

# Synthetic fixtures, not observed market values.
assert subset_percent("2", "5") == (Decimal("40.0"), "ok")
assert subset_percent(None, "5")[1] == "missing"
assert subset_percent("0", "0")[1] == "invalid_scope"
assert subset_percent("6", "5")[1] == "invalid_scope"
assert subset_percent("Infinity", "5")[1] == "nonfinite"
Enter fullscreen mode Exit fullscreen mode

The subset assumption matters. This function is not a generic ratio validator: growth rates and leverage ratios can legitimately exceed one hundred percent. It also cannot detect a numerator from one session paired with a denominator from another. That requires metadata validation before this arithmetic step.

For a real record, preserve the original inputs, source, unit and observation window alongside the classification. Do not silently clamp a bad percentage into the display range. A separately reported validation failure makes the source problem reviewable.

Reference: https://docs.python.org/3/library/decimal.html

Where the same idea shows up in a product screen

I work on SIGNUM HQ, a US-stock options and earnings app. Its public "Earnings verification receipts" page applies the same habit to a different problem: each row keeps the option session, option expiry, the stored capturedAt timestamp and a "pre-announcement timing unverified" status next to the numbers, instead of presenting every comparison as if it were a clean forecast. The screenshot below is the week of 2026-10-19.

SIGNUM HQ earnings verification receipts, week of 2026-10-19

Public page: https://www.signumhq.com/en/receipts/earnings?from=devto_1026
App: https://www.signumhq.com/app?from=devto_1026

This is an engineering note, not investment advice or a recommendation about any security.

Top comments (0)