Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions mathparse/mathparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,19 +85,23 @@ def to_number(val) -> Union[int, float, str, Decimal]:
"""
Convert a string to an int or float if possible.
"""
# If already a number (int, float, Decimal), return as-is
if isinstance(val, (int, float, Decimal)):
return val
# If already a number (Decimal), return as-is
if isinstance(val, Decimal):
return Decimal(val)

# Convert other numbers to Decimal
if isinstance(val, (int, float)):
return Decimal(val)

# Check if it's a constant and convert
if is_constant(val):
return mathwords.CONSTANTS[val]
return Decimal(mathwords.CONSTANTS[val])

# Otherwise, try to convert string to number
if is_int(val):
return int(val)
return Decimal(int(val))
elif is_float(val):
return float(val)
return Decimal(float(val))

return val

Expand Down
7 changes: 7 additions & 0 deletions tests/test_complex_statements.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,10 @@ def test_unicode_pi_in_expression(self):
"""
result = mathparse.parse('π + 1')
self.assertAlmostEqual(result, 3.141593 + 1, places=5)

def test_with_operations_and_single_numbers(self):
"""
Test using the unicode π symbol in a complex expression.
"""
result = mathparse.parse("(1 + 3 + 2.0 + 6) * 1")
self.assertAlmostEqual(result, 0.00012, places=5)