Skip to content
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

[Bug fix] Handle arithmetic overflow in BigDecimal#div #10628

Merged
merged 3 commits into from
Jun 4, 2021
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
3 changes: 3 additions & 0 deletions spec/std/big/big_decimal_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ describe BigDecimal do
BigDecimal.new(500.to_big_i, 0).should eq(BigDecimal.new(-1000) / BigDecimal.new(-2))
BigDecimal.new(0).should eq(BigDecimal.new(0) / BigDecimal.new(1))
BigDecimal.new("3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333".to_big_i, 100_u64).should eq(BigDecimal.new(1) / BigDecimal.new(3))
BigDecimal.new(-2000).should eq(BigDecimal.new(-0.02) / (BigDecimal.new(0.00001)))

BigDecimal.new(0).should eq(BigDecimal.new(1) // BigDecimal.new(2))
BigDecimal.new(-1).should eq(BigDecimal.new(1) // BigDecimal.new(-2))
Expand All @@ -183,6 +184,7 @@ describe BigDecimal do
BigDecimal.new(500).should eq(BigDecimal.new(-1000) // BigDecimal.new(-2))
BigDecimal.new(0).should eq(BigDecimal.new(0) // BigDecimal.new(1))
BigDecimal.new(0).should eq(BigDecimal.new(1) // BigDecimal.new(3))
BigDecimal.new(-2000).should eq(BigDecimal.new(-0.02) // (BigDecimal.new(0.00001)))

BigDecimal.new(33333.to_big_i, 5_u64).should eq(BigDecimal.new(1).div(BigDecimal.new(3), 5))
BigDecimal.new(33.to_big_i, 5_u64).should eq(BigDecimal.new(1).div(BigDecimal.new(3000), 5))
Expand Down Expand Up @@ -329,6 +331,7 @@ describe BigDecimal do

(BigDecimal.new("112839719283").div(BigDecimal.new("3123779"), 9)).to_s.should eq "36122.824080384"
(BigDecimal.new("112839719283").div(BigDecimal.new("3123779"), 14)).to_s.should eq "36122.8240803846879"
(BigDecimal.new("-0.4098").div(BigDecimal.new("0.2229011193"), 20)).to_s.should eq "-1.83848336557007141059"

BigDecimal.new(1, 2).to_s.should eq "0.01"
BigDecimal.new(100, 4).to_s.should eq "0.01"
Expand Down
7 changes: 6 additions & 1 deletion src/big/big_decimal.cr
Original file line number Diff line number Diff line change
Expand Up @@ -207,8 +207,13 @@ struct BigDecimal < Number
check_division_by_zero other
other.factor_powers_of_ten

scale = @scale - other.scale
numerator, denominator = @value, other.@value
scale = if @scale >= other.scale
@scale - other.scale
else
numerator *= TEN ** (other.scale - @scale)
0
end

quotient, remainder = numerator.divmod(denominator)
if remainder == ZERO
Expand Down