-
Notifications
You must be signed in to change notification settings - Fork 41
/
number.py
41 lines (34 loc) · 1.23 KB
/
number.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import re
import six
from decimal import Decimal
from ..config import ERROR
# Module API
def cast_number(format, value, **options):
group_char = options.get('groupChar', _DEFAULT_GROUP_CHAR)
decimal_char = options.get('decimalChar', _DEFAULT_DECIMAL_CHAR)
if not isinstance(value, Decimal):
if isinstance(value, six.string_types):
value = re.sub(r'\s', '', value)
value = value.replace(decimal_char, '__decimal_char__')
value = value.replace(group_char, '')
value = value.replace('__decimal_char__', '.')
if not options.get('bareNumber', _DEFAULT_BARE_NUMBER):
value = re.sub(r'((^\D*)|(\D*$))', '', value)
elif not isinstance(value, six.integer_types + (float,)):
return ERROR
try:
if isinstance(value, float):
value = str(value)
value = Decimal(value)
except Exception:
return ERROR
return value
# Internal
_DEFAULT_GROUP_CHAR = ''
_DEFAULT_DECIMAL_CHAR = '.'
_DEFAULT_BARE_NUMBER = True