Skip to content

Commit 445f464

Browse files
committed
fix: avoid double sign in Complex.to_string
1 parent cb66dc6 commit 445f464

File tree

2 files changed

+31
-4
lines changed

2 files changed

+31
-4
lines changed

lib/complex.ex

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -62,10 +62,16 @@ defmodule Complex do
6262
Conveniency function that is used to implement the `String.Chars` and `Inspect` protocols.
6363
"""
6464
def to_string(%Complex{re: re, im: im}) do
65-
if im < 0 do
66-
"#{re}-#{abs(im)}i"
67-
else
68-
"#{re}+#{im}i"
65+
cond do
66+
im < 0 ->
67+
"#{re}-#{abs(im)}i"
68+
69+
im == 0 ->
70+
# This is so we deal with -0.0 properly
71+
"#{re}+0.0i"
72+
73+
:otherwise ->
74+
"#{re}+#{im}i"
6975
end
7076
end
7177

test/complex_test.exs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,27 @@ defmodule ComplexTest do
192192
assert_close Complex.acoth(1.0049698), a
193193
end
194194

195+
for {m, f} <- [{Kernel, :inspect}, {String.Chars.Complex, :to_string}, {Complex, :to_string}] do
196+
test "#{m}.#{f}/1" do
197+
assert "1.0+1.0i" == apply(unquote(m), unquote(f), [Complex.new(1.0, 1.0)])
198+
assert "1.0-1.0i" == apply(unquote(m), unquote(f), [Complex.new(1.0, -1.0)])
199+
assert "1.0+0.0i" == apply(unquote(m), unquote(f), [Complex.new(1.0, 0.0)])
200+
assert "1.0+0.0i" == apply(unquote(m), unquote(f), [Complex.new(1.0, -0.0)])
201+
202+
assert "1.0-1.0i" ==
203+
apply(unquote(m), unquote(f), [Complex.new(1.0, 1.0) |> Complex.conjugate()])
204+
205+
assert "1.0+1.0i" ==
206+
apply(unquote(m), unquote(f), [Complex.new(1.0, -1.0) |> Complex.conjugate()])
207+
208+
assert "1.0+0.0i" ==
209+
apply(unquote(m), unquote(f), [Complex.new(1.0, 0.0) |> Complex.conjugate()])
210+
211+
assert "1.0+0.0i" ==
212+
apply(unquote(m), unquote(f), [Complex.new(1.0, -0.0) |> Complex.conjugate()])
213+
end
214+
end
215+
195216
defp assert_close(left, right, opts \\ []) do
196217
eps = opts[:eps] || 1.0e-5
197218

0 commit comments

Comments
 (0)