Skip to content

Raise ArgumentError if BigFloat initialized with invalid string #5638

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 25, 2018
Merged
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
6 changes: 6 additions & 0 deletions spec/std/big/big_float_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 3 additions & 1 deletion src/big/big_float.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down