Reputation: 2448
What is the best way to validate an input as a currency (without any currency symbols) My valid inputs can be only in the form of 40 or 40.12
Upvotes: 1
Views: 5819
Reputation:
I've been googling about an hour for proper way on how to do this. I haven't found any really good and safe way, and wrote regular expression below to match positive non-zero number with optional 1-2 digits after dot-separator:
re.match(r'^[1-9]\d*(\.\d{1,2})?$', val)
^
and $
: without matching whole string there will be ways to fooling up the regex.[1-9]
: first character always should be from 1 to 9\d*
: after first digit any amount of digits allowed(\.\d{1,2})?
: optional 1-2 digit fraction with dot-separator. Use [\.\,]
instead of \.
if multiple separator support is neededUpvotes: 0
Reputation: 4002
How about simply using format()
and try/except for wrong values?
>>> "{:.2f}".format(float("40.12"))
'40.12'
>>> "{:.2f}".format(float("40"))
'40.00'
>>> "{:.2f}".format(float("40.123"))
'40.12'
>>> try:
... "{:.2f}".format(float("40.123€"))
... except ValueError:
... "fail"
...
'fail'
Note that it simply cuts any number behind the second number behind the decimal point. You should be more specific by showing us more examples with your desired behaviour.
Upvotes: 5
Reputation: 500873
You could use a regular expression:
re.match(r'\d+(?:[.]\d{2})?$', '40.12')
This returns a match object if the input is correct, or None
if it isn't.
The above regex matches one or more digits optionally followed by a dot and exactly two more digits. This can be tweaked as required if I didn't capture your requirements precisely (the problem statement is somewhat open to interpretation).
Upvotes: 3