Skip to content

Commit

Permalink
[Bug fix] Handle arithmetic overflow in BigDecimal#div (#10628)
Browse files Browse the repository at this point in the history
* Handle arithmetic overflow in #div

* Add tests for bug fix

* Remove duplicate comparison
  • Loading branch information
kellydanma authored Jun 4, 2021
1 parent 08d1d37 commit 66a0e10
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
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

0 comments on commit 66a0e10

Please sign in to comment.