Skip to content

Commit 00795cb

Browse files
committed
Support a Complex in Kernel.BigDecimal()
1 parent 77c64be commit 00795cb

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

ext/bigdecimal/bigdecimal.c

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2631,6 +2631,7 @@ VpNewVarArg(int argc, VALUE *argv)
26312631
}
26322632
}
26332633

2634+
retry:
26342635
switch (TYPE(iniValue)) {
26352636
case T_DATA:
26362637
if (is_kind_of_BigDecimal(iniValue)) {
@@ -2668,6 +2669,18 @@ VpNewVarArg(int argc, VALUE *argv)
26682669
}
26692670
return GetVpValueWithPrec(iniValue, mf, 1);
26702671

2672+
case T_COMPLEX:
2673+
{
2674+
VALUE im;
2675+
im = rb_complex_imag(iniValue);
2676+
if (!is_zero(im)) {
2677+
rb_raise(rb_eArgError,
2678+
"Unable to make a BigDecimal from non-zero imaginary number");
2679+
}
2680+
iniValue = rb_complex_real(iniValue);
2681+
goto retry;
2682+
}
2683+
26712684
case T_STRING:
26722685
/* fall through */
26732686
default:

test/bigdecimal/test_bigdecimal.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,14 @@ def test_BigDecimal_with_float
137137
end
138138
end
139139

140+
def test_BigDecimal_with_complex
141+
assert_equal(BigDecimal("1"), BigDecimal(Complex(1, 0)))
142+
assert_equal(BigDecimal("0.333333333333333333333"), BigDecimal(Complex(1.quo(3), 0), 21))
143+
assert_equal(BigDecimal("0.1235"), BigDecimal(Complex(0.1234567, 0), 4))
144+
145+
assert_raise_with_message(ArgumentError, "Unable to make a BigDecimal from non-zero imaginary number") { BigDecimal(Complex(1, 1)) }
146+
end
147+
140148
def test_BigDecimal_with_big_decimal
141149
assert_equal(BigDecimal(1), BigDecimal(BigDecimal(1)))
142150
assert_equal(BigDecimal('+0'), BigDecimal(BigDecimal('+0')))

0 commit comments

Comments
 (0)