From a4930d268dcb2abad8cc286aecd82cdf51d24334 Mon Sep 17 00:00:00 2001 From: s3lph Date: Fri, 20 Jul 2018 15:25:06 +0200 Subject: [PATCH] Added code comments to parse_chf. --- matemat/webserver/util.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/matemat/webserver/util.py b/matemat/webserver/util.py index 74041d8..cd0d2ef 100644 --- a/matemat/webserver/util.py +++ b/matemat/webserver/util.py @@ -168,21 +168,27 @@ def parse_chf(value: str) -> int: :return: An integer representation of the value. :raises: Value error: If more than two digits after the decimal point are present. """ + # Remove optional leading "CHF" and strip whitespace value = value.strip() if value.startswith('CHF'): value = value[3:] value = value.strip() if '.' not in value: + # already is an integer; parse and turn into centimes return int(value, 10) * 100 + # Split at the decimal point full, frac = value.split('.', 1) if len(frac) > 2: raise ValueError('Needs max. 2 digits after decimal point') elif len(frac) < 2: + # Right-pad fraction with zeros ("x." -> "x.00", "x.x" -> "x.x0") frac = frac + '0' * (2 - len(frac)) + # Parse both parts ifrac: int = int(frac, 10) ifull: int = int(full, 10) if ifrac < 0: raise ValueError('Fraction part must not be negative.') if full.startswith('-'): ifrac = -ifrac + # Combine into centime integer return ifull * 100 + ifrac