Skip to content

Commit

Permalink
Support floats like 1.0 for integer casting (#216)
Browse files Browse the repository at this point in the history
* Support float for integer casting

Added support for float or decimal types in integer casting. Casting only occurs if the float or decimal is already intger-like, otherwise it returns ERROR

* updated integer test
  • Loading branch information
vincentchevrier authored and roll committed Aug 16, 2018
1 parent d47b6d7 commit 0e9045f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
22 changes: 19 additions & 3 deletions tableschema/types/integer.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,37 @@

import re
import six
from decimal import Decimal
from ..config import ERROR


# Module API


def cast_integer(format, value, **options):
if not isinstance(value, six.integer_types):
if not isinstance(value, six.string_types):
return ERROR
if isinstance(value, six.integer_types):
pass

elif isinstance(value, six.string_types):
if not options.get('bareNumber', _DEFAULT_BARE_NUMBER):
value = re.sub(r'((^\D*)|(\D*$))', '', value)

try:
value = int(value)
except Exception:
return ERROR

elif isinstance(value, float):
if value.is_integer():
value = int(value)

elif isinstance(value, Decimal):
if value % 1 == 0:
value = int(value)

else:
return ERROR

return value


Expand Down
1 change: 1 addition & 0 deletions tests/types/test_integer.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
('default', 1, 1, {}),
('default', 1 << 63, 1 << 63, {}),
('default', '1', 1, {}),
('default', 1.0, 1, {}),
('default', '1$', 1, {'bareNumber': False}),
('default', 'ab1$', 1, {'bareNumber': False}),
('default', '3.14', ERROR, {}),
Expand Down

0 comments on commit 0e9045f

Please sign in to comment.