runtime
467 / 500
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.

Functionparse_amount(text)
Format1 to 5 ASCII digits, optionally a . and 1 or 2 more digits: 12, 12.5, 12.50
Rangemore than 0 and at most 10000
Returnsthe amount as a Decimal (Decimal("12.50") for "12.50")
RaisesValueError for anything else
Examples
callparse_amount('abc')raisesValueError
callparse_amount('1e3')raisesValueError
callparse_amount('12.505')raisesValueError

Loading your progress…

Parse a money amount from a form — Python practice · Runtime