Issue
As of title, I need to remove commas from string number and leave decimal point, but the problem is input can be with .
or ,
. This input will be saved for Django model's DecimalField
For example:
Input:
"250,000,50"
"250,000"
"250000.00"
"25,000"
Output:
250000.50
250000.00
250000.00
25000.00
What I have tried:
def _normalize_amount(self, value -> str):
normalized_amount = value[:-3].replace(",", "") + value[-3:]
return Decimal(normalized_amount)
Problem is that this function can not handle the cases where user enters ,
as decimal point. How to solve this case ?
Solution
You can search if the number has one or two digits after last decimal point, e.g.:
import re
text = """\
250,000,50
250,000
250000.00
25,000"""
pat = r"([\d,.]+?)([,.]\d{,2})?$"
for a1, a2 in re.findall(pat, text, flags=re.M):
print("".join(re.findall(r"\d+", a1)) + f".{a2[1:].zfill(2)}")
Prints:
250000.50
250000.00
250000.00
25000.00
Answered By - Andrej Kesely
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.