How to parse string to int or float in Python using UliEngineering

You can easily parse a string to either an integer or float using the UliEngineering Python library:

parse_int_or_float.py
from UliEngineering.Utils.Parser import parse_int_or_float

# Parse integer strings
value = parse_int_or_float("42")
print(f"Parse '42': {value} (type: {type(value).__name__})")

# Parse float strings
value = parse_int_or_float("3.14")
print(f"Parse '3.14': {value} (type: {type(value).__name__})")

# Parse scientific notation
value = parse_int_or_float("1.5e3")
print(f"Parse '1.5e3': {value} (type: {type(value).__name__})")

Example output

parse_int_or_float_output.txt
Parse '42': 42 (type: int)
Parse '3.14': 3.14 (type: float)
Parse '1.5e3': 1500.0 (type: float)

This function automatically determines whether to return an integer or float based on the input string. Integer strings without decimal points are returned as int, while strings with decimal points or scientific notation are returned as float. This is useful when you need to handle numeric input that could be either integer or floating-point without knowing the type in advance.


Check out similar posts by category: Python, Utilities