Skip to content

Commit

Permalink
fix the creation of BigDecimal from a String
Browse files Browse the repository at this point in the history
follow what MRI is doing and ignore the precision

fixes #2650

Sponsored by Lookout Inc.
  • Loading branch information
mkristian committed Mar 20, 2015
1 parent aabe84c commit 5f4bb39
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
Expand Up @@ -526,7 +526,9 @@ public static RubyBigDecimal newInstance(IRubyObject recv, IRubyObject[] args) {
MathContext context = MathContext.UNLIMITED;

if (args.length == 2) {
System.err.println( "margs" + args[1]);
int digits = (int)args[1].convertToInteger().getLongValue();
System.err.println( "margs" + digits);
if (digits < 0) {
throw runtime.newArgumentError("argument must be positive");
}
Expand Down Expand Up @@ -562,6 +564,8 @@ public static RubyBigDecimal newInstance(IRubyObject recv, IRubyObject[] args) {
return new RubyBigDecimal(runtime, (RubyClass)recv, new BigDecimal(((RubyFixnum)args[0]).getLongValue(), context));
} else if (args[0] instanceof RubyBignum) {
return new RubyBigDecimal(runtime, (RubyClass)recv, new BigDecimal(((RubyBignum)args[0]).getBigIntegerValue(), context));
} else {
context = MathContext.UNLIMITED;
}
// fall through to String coercion below
}
Expand Down Expand Up @@ -592,7 +596,10 @@ public static RubyBigDecimal newInstance(IRubyObject recv, IRubyObject[] args) {
strValue = NUMBER_PATTERN.matcher(strValue).replaceFirst("$1");

try {
System.err.println("newInstance " + strValue );
System.err.println("newInstance " + context );
decimal = new BigDecimal(strValue, context);
System.err.println("newInstance " + decimal );
} catch(NumberFormatException e) {
if (isOverflowExceptionMode(runtime)) {
throw runtime.newFloatDomainError("exponent overflow");
Expand Down Expand Up @@ -1769,6 +1776,7 @@ public IRubyObject sqrt(IRubyObject arg) {

@JRubyMethod(name = "to_f")
public IRubyObject to_f() {
System.err.println("to_f " + value );
if (isNaN()) {
return RubyFloat.newFloat(getRuntime(), Double.NaN);
}
Expand Down
8 changes: 7 additions & 1 deletion test/test_bignum.rb
@@ -1,4 +1,5 @@
require 'test/unit'
require 'bigdecimal'

class TestBignum < Test::Unit::TestCase
# others tested in FixnumBignumAutoconversion test
Expand Down Expand Up @@ -41,6 +42,11 @@ def test_bignum_should_respond_to_array_operator
def test_bignum_aref_with_bignum_arg_no_exception
assert_equal(0, (2**64)[2**32])
end

def test_GH_2650
assert_equal(BigDecimal.new("10.91231", 1).to_f, 10.91231)
assert_equal(BigDecimal.new("10.9", 2).to_f, 10.9)
end
# more to come

end
end

0 comments on commit 5f4bb39

Please sign in to comment.