diff --git a/spec/std/big/big_float_spec.cr b/spec/std/big/big_float_spec.cr index 84332b8dc079..98c711c7a35f 100644 --- a/spec/std/big/big_float_spec.cr +++ b/spec/std/big/big_float_spec.cr @@ -15,6 +15,12 @@ describe "BigFloat" do BigFloat.new("-#{string_of_integer_value}").to_s.should eq("-#{string_of_integer_value}") end + it "raises an ArgumentError unless string denotes valid float" do + expect_raises(ArgumentError) { BigFloat.new("abc") } + expect_raises(ArgumentError) { BigFloat.new("+") } + expect_raises(ArgumentError) { BigFloat.new("") } + end + it "new(BigInt)" do bigfloat_on_bigint_value = BigFloat.new(BigInt.new(string_of_integer_value)) bigfloat_on_bigint_value.should eq(bigfloat_of_integer_value) diff --git a/src/big/big_float.cr b/src/big/big_float.cr index 6a7269a3af5b..29d0da0969f7 100644 --- a/src/big/big_float.cr +++ b/src/big/big_float.cr @@ -15,7 +15,9 @@ struct BigFloat < Float def initialize(str : String) # Strip leading '+' char to smooth out cases with strings like "+123" str = str.lchop('+') - LibGMP.mpf_init_set_str(out @mpf, str, 10) + if LibGMP.mpf_init_set_str(out @mpf, str, 10) == -1 + raise ArgumentError.new("Invalid BigFloat: #{str.inspect}") + end end def initialize(num : BigInt)