Skip to content

Commit

Permalink
Fix unexpected java.lang.ArithmeticException
Browse files Browse the repository at this point in the history
when converting Rational to BigDecimal
Fixes jruby#4324
  • Loading branch information
kirs committed Nov 26, 2016
1 parent d081169 commit bf6d141
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
11 changes: 8 additions & 3 deletions core/src/main/java/org/jruby/ext/bigdecimal/RubyBigDecimal.java
Expand Up @@ -487,7 +487,12 @@ private static RubyBigDecimal newInstance(Ruby runtime, IRubyObject recv, RubyFi
private static RubyBigDecimal newInstance(ThreadContext context, RubyRational arg, MathContext mathContext) {
BigDecimal num = new BigDecimal(arg.numerator(context).convertToInteger().getLongValue());
BigDecimal den = new BigDecimal(arg.denominator(context).convertToInteger().getLongValue());
BigDecimal value = num.divide(den, mathContext);
BigDecimal value;
try {
value = num.divide(den, mathContext);
} catch (ArithmeticException e){
value = num.divide(den, MathContext.DECIMAL64);
};

return new RubyBigDecimal(context.runtime, value);
}
Expand Down Expand Up @@ -550,7 +555,7 @@ else if (isExponentOutOfRange(expValue)) {
else if ( ( idx = matcher.start(3) ) > 0 ) {
strValue = strValue.substring(0, idx); // ignored tail junk e.g. "5-6" -> "-6"
}

BigDecimal decimal;
try {
decimal = new BigDecimal(strValue, mathContext);
Expand Down Expand Up @@ -1382,7 +1387,7 @@ public IRubyObject round(ThreadContext context, IRubyObject[] args) {
} else {
bigDecimal = new RubyBigDecimal(context.runtime, value.setScale(scale, mode));
}

return args.length == 0 ? bigDecimal.to_int() : bigDecimal;
}

Expand Down
1 change: 1 addition & 0 deletions test/mri/bigdecimal/test_bigdecimal.rb
Expand Up @@ -75,6 +75,7 @@ def test_global_new_with_integer
end

def test_global_new_with_rational
assert_equal(BigDecimal("0.3333333333333333E0"), BigDecimal(Rational(1, 3), 0))
assert_equal(BigDecimal("0.333333333333333333333"), BigDecimal(1.quo(3), 21))
assert_equal(BigDecimal("-0.333333333333333333333"), BigDecimal(-1.quo(3), 21))
assert_raise(ArgumentError) { BigDecimal(1.quo(3)) }
Expand Down

0 comments on commit bf6d141

Please sign in to comment.