28 lines
732 B
Python
28 lines
732 B
Python
import re
|
|
|
|
|
|
class InvalidStringException(Exception):
|
|
"""Raised when a string cannot be converted to an integer."""
|
|
pass
|
|
|
|
|
|
def convert_string_to_integer(data: str) -> int | Exception:
|
|
"""
|
|
Converts a string to an integer value.
|
|
:param data: A string containing an integer or float value to convert
|
|
:return: The converted integer value or exception object
|
|
|
|
Examples:
|
|
>>> convert_string_to_integer("4")
|
|
4
|
|
>>> convert_string_to_integer("3.0")
|
|
3
|
|
"""
|
|
|
|
try:
|
|
if '.' in data:
|
|
return int(float(data))
|
|
else:
|
|
return int(data)
|
|
except ValueError as exc:
|
|
raise InvalidStringException("The string could not be converted to an integer.") from exc |