Skip to content

Handle negative imaginary parts in number_to_string (#551) - #598

Merged
seperman merged 1 commit into
qlustered:devfrom
koriyoshi2041:fix/number-to-string-negative-imaginary
Jul 29, 2026
Merged

Handle negative imaginary parts in number_to_string (#551)#598
seperman merged 1 commit into
qlustered:devfrom
koriyoshi2041:fix/number-to-string-negative-imaginary

Conversation

@koriyoshi2041

Copy link
Copy Markdown

Fixes #551.

number_to_string reconstructs complex numbers by formatting then re-parsing:

number = number.__class__(
    "{real}+{imag}j".format(real=..., imag=...)
)

When the imaginary part is negative, the formatted imag already starts with -, so the literal + produces an invalid string such as "1.0+-1.0j", and complex("1.0+-1.0j") raises ValueError: complex() arg is a malformed string.

>>> from deepdiff.helper import number_to_string
>>> number_to_string(1-1j, significant_digits=1)
ValueError: complex() arg is a malformed string
>>> from deepdiff import DeepHash
>>> DeepHash(1-1j, significant_digits=3)   # same crash

The fix joins real and imag using the imaginary part's own sign, so negative imaginary parts produce "1.0-1.0j" instead of "1.0+-1.0j". Positive parts are unchanged.

The existing test_number_to_string_complex_digits cases only exercised non-negative (or rounds-to-zero) imaginary parts. Added two cases with non-zero negative imaginary parts (which raised before the fix); the full parametrized test passes.

number_to_string rebuilt complex numbers via "{real}+{imag}j".format(...).
When the imaginary part is negative this produced an invalid string like
"1.0+-1.0j", and the complex() round-trip raised ValueError -- so
number_to_string(1-1j) and, by extension, DeepHash(1-1j, significant_digits=3)
crashed. Join using the imaginary part's own sign instead.

@seperman seperman left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@seperman
seperman changed the base branch from master to dev July 29, 2026 17:01
@seperman
seperman merged commit 611fbb3 into qlustered:dev Jul 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Common ValueError raised when formatting complex numbers

2 participants