Skip to content

Commit 697b89c

Browse files
amount separators
1 parent f3e8bec commit 697b89c

File tree

1 file changed

+42
-7
lines changed

1 file changed

+42
-7
lines changed

sipay/amount.py

Lines changed: 42 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,39 @@
66
class Amount:
77
"""Amount class."""
88

9-
def __init__(self, amount, currency):
9+
def __init__(self, amount, currency, separator='', decimal_separator='.'):
1010
"""Initialize Amount."""
1111
self.currency = currency
12-
index = -self._currency[2]-1
13-
if isinstance(amount, str) and \
14-
re.match(r'^([0-9]+\.[0-9]+)$', amount) and amount[index] == '.':
15-
amount = amount.replace('.', '')
16-
amount = int(amount)
12+
self.separator = separator
13+
self.decimal_separator = decimal_separator
14+
15+
if isinstance(amount, str):
16+
if not isinstance(separator, str) or len(separator) >= 2 or \
17+
re.match(r'[0-9]', separator):
18+
raise TypeError('separator must be a string with length 0,1.')
19+
20+
if not isinstance(decimal_separator, str) or \
21+
len(decimal_separator) != 1 or \
22+
re.match(r'[0-9]', decimal_separator):
23+
raise TypeError('decimal_separator must be a string with '
24+
'length 1.')
25+
26+
if decimal_separator == separator:
27+
raise TypeError('separators are equals.')
28+
29+
if len(separator) == 1:
30+
separator = "\{}".format(separator)
31+
32+
decimal_separator = "\{}".format(decimal_separator)
33+
34+
regex = '^[0-9]{{1,3}}({sep}[0-9]{{3}})*{decimal_sep}[0-9]'\
35+
'{{{decimals}}}$'.format(sep=separator,
36+
decimal_sep=decimal_separator,
37+
decimals=self._currency[2])
38+
if re.match(regex, amount):
39+
amount = amount.replace(self.decimal_separator, '')
40+
amount = amount.replace(self.separator, '')
41+
amount = int(amount)
1742

1843
self.amount = amount
1944

@@ -131,4 +156,14 @@ def __str__(self):
131156
"""Parse to string."""
132157
dec = self._currency[2]
133158
fmt_amount = str(self.amount).zfill(dec + 1)
134-
return fmt_amount[:-dec] + '.' + fmt_amount[-dec:] + self.currency
159+
decimal = fmt_amount[-dec:]
160+
integer = fmt_amount[:-dec]
161+
length = len(integer)
162+
init = length%3 if length%3 > 0 else 3;
163+
integer_ftm = integer[:init]
164+
165+
for i in range(init, length, 3):
166+
integer_ftm += "{0}{1}".format(self.separator, integer[i:i+3])
167+
168+
169+
return integer_ftm + self.decimal_separator + decimal + self.currency

0 commit comments

Comments
 (0)