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
10 changes: 9 additions & 1 deletion ext/bigdecimal/bigdecimal.c
Original file line number Diff line number Diff line change
Expand Up @@ -1864,7 +1864,15 @@ BigDecimal_div2(VALUE self, VALUE b, VALUE n)
// ROUND_UP cv = 0.1e0 with idx=10 will be:
// 0.1e0 if remainder == 0
// 0.1000000001e0 if remainder != 0
size_t idx = roomof(ix, BASE_FIG);
// frac[idx] must be the first word after the ix-th digit, so count
// the leading zeros of frac[0] too (9.0909... is 000000009_090909090_...).
size_t leading_zeros = BASE_FIG;
DECDIG v = cv.real->frac[0];
while (v) {
v /= 10;
leading_zeros--;
}
size_t idx = roomof(ix + leading_zeros, BASE_FIG);
while (cv.real->Prec <= idx) cv.real->frac[cv.real->Prec++] = 0;
if (cv.real->frac[idx] == 0 || cv.real->frac[idx] == HALF_BASE) cv.real->frac[idx]++;
}
Expand Down
10 changes: 10 additions & 0 deletions test/bigdecimal/test_bigdecimal.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1210,6 +1210,16 @@ def test_div_rounding_with_small_remainder
assert_equal(BigDecimal("0.100000000000000000000000000001e1"), BigDecimal("3.#{'0' * 40}1").div(3, 30))
assert_equal(BigDecimal("0.10000000000000000001e1"), BigDecimal("3.#{'0' * 40}1").div(3, 20))
assert_equal(BigDecimal("0.10000000000000000001e6"), BigDecimal("3.#{'0' * 40}1e5").div(3, 20))

# The first word of the quotient has leading zeros (9.0909... is stored as 000000009_090909090_...)
assert_equal(BigDecimal("0.909090909090909090909090910e1"), BigDecimal(6).div(BigDecimal("0.66"), 27))
assert_equal(BigDecimal("-0.123750001e-78"), BigDecimal("-495e-18").div(BigDecimal("3#{'9' * 40}e23"), 9))

# 1.000000005 / 0.999...9 = 1.000000005000...0001000000005...
BigDecimal.mode(BigDecimal::ROUND_MODE, BigDecimal::ROUND_HALF_DOWN)
assert_equal(BigDecimal("0.100000001e1"), BigDecimal("1.000000005").div(BigDecimal("0.#{'9' * 40}"), 9))
BigDecimal.mode(BigDecimal::ROUND_MODE, BigDecimal::ROUND_HALF_EVEN)
assert_equal(BigDecimal("0.100000001e1"), BigDecimal("1.000000005").div(BigDecimal("0.#{'9' * 40}"), 9))
end

def test_div_with_float
Expand Down