|
6 | 6 | class Amount:
|
7 | 7 | """Amount class."""
|
8 | 8 |
|
9 |
| - def __init__(self, amount, currency): |
| 9 | + def __init__(self, amount, currency, separator='', decimal_separator='.'): |
10 | 10 | """Initialize Amount."""
|
11 | 11 | 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) |
17 | 42 |
|
18 | 43 | self.amount = amount
|
19 | 44 |
|
@@ -131,4 +156,14 @@ def __str__(self):
|
131 | 156 | """Parse to string."""
|
132 | 157 | dec = self._currency[2]
|
133 | 158 | 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