Skip to content

Commit

Permalink
Fix division for negative values
Browse files Browse the repository at this point in the history
  • Loading branch information
timcraft committed Sep 5, 2024
1 parent dc229b0 commit 98b492c
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/monies.rb
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,7 @@ def zero?
def divide(value, scale, divisor, max_scale)
quotient, carry = 0, 0

value.digits.reverse_each do |digit|
value.abs.digits.reverse_each do |digit|
dividend = carry + digit

quotient = (quotient * BASE) + (dividend / divisor)
Expand All @@ -411,6 +411,8 @@ def divide(value, scale, divisor, max_scale)
iterations -= 1
end

quotient = -quotient if value.negative?

self.class.new(quotient, scale, @currency)
end

Expand Down
6 changes: 6 additions & 0 deletions spec/monies_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,9 @@
expect(Monies.new(92, 2, 'GBP') / Monies.new(4, 1, 'GBP')).to eq(Monies.new(23, 1, 'GBP'))
expect(Monies.new(12, 5, 'GBP') / Monies.new(8, 3, 'GBP')).to eq(Monies.new(15, 3, 'GBP'))
expect(Monies.new(1, 1, 'GBP') / Monies.new(5, 4, 'GBP')).to eq(Monies.new(200, 0, 'GBP'))
expect(Monies.new(100, 0, 'GBP') / Monies.new(-20, 0, 'GBP')).to eq(Monies.new(-5, 0, 'GBP'))
expect(Monies.new(-100, 0, 'GBP') / Monies.new(20, 0, 'GBP')).to eq(Monies.new(-5, 0, 'GBP'))
expect(Monies.new(-100, 0, 'GBP') / Monies.new(-20, 0, 'GBP')).to eq(Monies.new(5, 0, 'GBP'))
end
end

Expand All @@ -299,6 +302,9 @@
expect(Monies.new(1224, 3, 'GBP') / 8).to eq(Monies.new(153, 3, 'GBP'))
expect(Monies.new(917, 0, 'GBP') / 6).to eq(Monies.new(1528333333333333333, 16, 'GBP'))
expect(Monies.new(1999, 3, 'GBP') / 3).to eq(Monies.new(6663333333333333, 16, 'GBP'))
expect(Monies.new(888, 0, 'GBP') / -8).to eq(Monies.new(-111, 0, 'GBP'))
expect(Monies.new(-888, 0, 'GBP') / 8).to eq(Monies.new(-111, 0, 'GBP'))
expect(Monies.new(-888, 0, 'GBP') / -8).to eq(Monies.new(111, 0, 'GBP'))
end
end

Expand Down

0 comments on commit 98b492c

Please sign in to comment.