question 467 Secure Python · medium
Parse a money amount from a form
The refund form has an amount field. Decimal() and float() both accept far more than a refund amount (1e3, NaN, Infinity, -5, 12), so read the text against a strict allow-list and return an exact Decimal.
Function
parse_amount(text)Format1 to 5 ASCII digits, optionally a
. and 1 or 2 more digits: 12, 12.5, 12.50Rangemore than 0 and at most 10000
Returnsthe amount as a
Decimal (Decimal("12.50") for "12.50")Raises
ValueError for anything elseExamples
callparse_amount('abc')raisesValueError
callparse_amount('1e3')raisesValueError
callparse_amount('12.505')raisesValueError