Skip to content

Commit 900bb7f

Browse files
committed
Allow passing both float and precision in BigDecimal#div
Fix GH-212.
1 parent 3cbc0c3 commit 900bb7f

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

ext/bigdecimal/bigdecimal.c

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1938,11 +1938,15 @@ BigDecimal_div2(VALUE self, VALUE b, VALUE n)
19381938
Real *res = NULL;
19391939
Real *av = NULL, *bv = NULL, *cv = NULL;
19401940
size_t mx = ix + VpBaseFig()*2;
1941+
size_t b_prec = ix;
19411942
size_t pl = VpSetPrecLimit(0);
19421943

19431944
GUARD_OBJ(cv, VpCreateRbObject(mx + VpBaseFig(), "0", true));
19441945
GUARD_OBJ(av, GetVpValue(self, 1));
1945-
GUARD_OBJ(bv, GetVpValue(b, 1));
1946+
if (RB_FLOAT_TYPE_P(b) && b_prec > BIGDECIMAL_DOUBLE_FIGURES) {
1947+
b_prec = BIGDECIMAL_DOUBLE_FIGURES;
1948+
}
1949+
GUARD_OBJ(bv, GetVpValueWithPrec(b, b_prec, 1));
19461950
mx = av->Prec + bv->Prec + 2;
19471951
if (mx <= cv->MaxPrec) mx = cv->MaxPrec + 1;
19481952
GUARD_OBJ(res, VpCreateRbObject((mx * 2 + 2)*VpBaseFig(), "#0", true));

test/bigdecimal/test_bigdecimal.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1091,6 +1091,16 @@ def test_div_bigdecimal
10911091
end
10921092
end
10931093

1094+
def test_div_bigdecimal_with_float_and_precision
1095+
x = BigDecimal(5)
1096+
y = 5.1
1097+
assert_equal(x.div(BigDecimal(y, 0), 8),
1098+
x.div(y, 8))
1099+
1100+
assert_equal(x.div(BigDecimal(y, 0), 100),
1101+
x.div(y, 100))
1102+
end
1103+
10941104
def test_abs_bigdecimal
10951105
x = BigDecimal((2**100).to_s)
10961106
assert_equal(1267650600228229401496703205376, x.abs)

0 commit comments

Comments
 (0)