OpenViSTAI · Agents · Blockchain · Crypto
Menu
OPENVIST RECIPES

Sum decimal amount strings with an explicit scale and no rounding

Python

Aggregate amounts exactly and reject silent precision loss.

Python code excerpt: Sum decimal amount strings with an explicit scale and no rounding. Version 1.0.0. Read the full recipe for code, sources and recorded test scope.

Aggregate amounts exactly and reject silent precision loss. This stdin-based Python CLI processes one bounded JSON request and returns the documented JSON result. It does not execute jobs or contact external services. Inspect its limits before adapting it to an application.

Before you start

  • Python 3.12 standard library; no third-party packages. Verified with the recorded pinned runtime.
  • One UTF-8 JSON object on stdin, no command-line arguments. Maximum encoded request size is 20000 bytes.

Build and check

  1. Save the source as sum-decimal-amounts-python.py.
  2. Save the example JSON below as request.json.
  3. Run python3 sum-decimal-amounts-python.py < request.json.
  4. Compare the parsed JSON result with the expected output. Invalid input exits 2 with empty stdout and a generic stderr message.

Limits to understand

  • Input is limited to 20000 bytes, 500 amounts, and an integer scale from 0 through 6.
  • Amounts must follow the specified decimal string grammar; fractional digits exceeding the scale are rejected, including trailing zeros. No rounding is performed.
  • This does not convert currencies, apply exchange rates, calculate taxes, or implement any financial policy.
  • Input exactly {"amounts":array of at most 500 strings,"scale":integer 0..6}; booleans forbidden.
  • Amount grammar: optional minus, then 0 or a nonzero ASCII digit followed by up to 8 digits; optionally dot and 1..6 ASCII fractional digits. Reject whitespace, plus, leading zeros, exponent and fraction longer than scale even when trailing zeros.
  • Use scaled integers or exact Decimal; no binary float. Output {"total":sum formatted with exactly scale fractional digits, or no dot when scale=0,"count":number_of_amounts}. Normalize negative zero.
  • This does not convert currencies, apply exchange rates, taxes or any financial policy.
  • The complete encoded input is limited to 20000 bytes; one additional byte can be read to detect overflow.
  • This is a bounded local helper. Passing the recorded cases does not verify every input, every Python version or an external integration.

Run it

python3 sum-decimal-amounts-python.py < request.json

Example input

{"amounts": ["0.10", "0.2", "-0.05"], "scale": 2}

Expected output

{"total":"0.25","count":3}
INSPECT THE SCRIPT

Inspect, copy and run the documented checks.

This browser preview builds code locally. It does not contact an API or run the code.

Default example ready.

Python example
import json
import re
import sys


AMOUNT = re.compile(r'-?(?:0|[1-9][0-9]{0,8})(?:\.[0-9]{1,6})?', re.ASCII)


def reject_number(_):
    raise ValueError('invalid input')


def unique_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError('invalid input')
        result[key] = value
    return result


def check_unicode(value):
    if isinstance(value, str):
        if any(0xD800 <= ord(char) <= 0xDFFF for char in value):
            raise ValueError('invalid input')
    elif isinstance(value, list):
        for item in value:
            check_unicode(item)
    elif isinstance(value, dict):
        for key, item in value.items():
            check_unicode(key)
            check_unicode(item)


def run():
    if len(sys.argv) != 1:
        raise ValueError('invalid input')
    raw = sys.stdin.buffer.read(20001)
    if len(raw) > 20000:
        raise ValueError('invalid input')
    text = raw.decode('utf-8', errors='strict')
    data = json.loads(
        text,
        object_pairs_hook=unique_object,
        parse_float=reject_number,
        parse_constant=reject_number,
    )
    check_unicode(data)
    if type(data) is not dict or set(data) != {'amounts', 'scale'}:
        raise ValueError('invalid input')
    scale = data['scale']
    amounts = data['amounts']
    if type(scale) is not int or not 0 <= scale <= 6:
        raise ValueError('invalid input')
    if type(amounts) is not list or len(amounts) > 500:
        raise ValueError('invalid input')

    factor = 10 ** scale
    total = 0
    for amount in amounts:
        if type(amount) is not str or AMOUNT.fullmatch(amount) is None:
            raise ValueError('invalid input')
        negative = amount.startswith('-')
        magnitude = amount[1:] if negative else amount
        whole, dot, fraction = magnitude.partition('.')
        if len(fraction) > scale:
            raise ValueError('invalid input')
        units = int(whole) * factor
        if dot:
            units += int(fraction) * (10 ** (scale - len(fraction)))
        total += -units if negative else units

    magnitude = abs(total)
    sign = '-' if total < 0 else ''
    if scale:
        whole, fraction = divmod(magnitude, factor)
        formatted = sign + str(whole) + '.' + str(fraction).zfill(scale)
    else:
        formatted = sign + str(magnitude)
    return json.dumps(
        {'total': formatted, 'count': len(amounts)},
        separators=(',', ':'),
    )


def main():
    try:
        output = run()
    except (ValueError, UnicodeError, RecursionError, OverflowError):
        sys.stderr.write('Invalid input\n')
        return 2
    sys.stdout.write(output + '\n')
    return 0


if __name__ == '__main__':
    sys.exit(main())
What to verify after running
  • Run the documented example and compare the JSON result.
  • Confirm malformed requests exit 2 without copying input data into diagnostic messages.
  • 22 independent CLI cases passed on this exact source, including an unexpected-argument check.

Request or format preview

Illustrative preview. No provider response, price or balance is fetched.

Change a setting to inspect the preview.

Official sources and related profiles

    Code license: MIT. Keep the license notice with your copy.

    Example version 1.0.0 · Documentation reviewed 2026-11-17.

    22 recorded CLI cases passed in rootless Docker on the pinned Python 3.12 runtime, with 512 MiB RAM, 1 CPU, no network, and read-only source. Other runtimes and all possible inputs are not verified.