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

Add BigDecimal#% #13255

Merged
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
15 changes: 15 additions & 0 deletions spec/std/big/big_decimal_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,21 @@ describe BigDecimal do
BigDecimal.new(3333.to_big_i, 7_u64).should eq(BigDecimal.new(1).div(BigDecimal.new(3000), 7))

(-BigDecimal.new(3)).should eq(BigDecimal.new(-3))

(BigDecimal.new(5) % BigDecimal.new(2)).should eq(BigDecimal.new(1))
(BigDecimal.new(500) % BigDecimal.new(2)).should eq(BigDecimal.new(0))
(BigDecimal.new(500) % BigDecimal.new(2000)).should eq(BigDecimal.new(500))
end

it "handles modulus correctly" do
(BigDecimal.new(13.0) % BigDecimal.new(4.0)).should eq(BigDecimal.new(1.0))
(BigDecimal.new(13.0) % BigDecimal.new(-4.0)).should eq(BigDecimal.new(-3.0))
(BigDecimal.new(-13.0) % BigDecimal.new(4.0)).should eq(BigDecimal.new(3.0))
(BigDecimal.new(-13.0) % BigDecimal.new(-4.0)).should eq(BigDecimal.new(-1.0))
(BigDecimal.new(11.5) % BigDecimal.new(4.0)).should eq(BigDecimal.new(3.5))
(BigDecimal.new(11.5) % BigDecimal.new(-4.0)).should eq(BigDecimal.new(-0.5))
(BigDecimal.new(-11.5) % BigDecimal.new(4.0)).should eq(BigDecimal.new(0.5))
(BigDecimal.new(-11.5) % BigDecimal.new(-4.0)).should eq(BigDecimal.new(-3.5))
end

it "performs arithmetic with other number types" do
Expand Down
16 changes: 16 additions & 0 deletions src/big/big_decimal.cr
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,22 @@ struct BigDecimal < Number
self * BigDecimal.new(other)
end

def %(other : BigDecimal) : BigDecimal
if @scale > other.scale
scaled = other.scale_to(self)
BigDecimal.new(@value % scaled.value, @scale)
elsif @scale < other.scale
scaled = scale_to(other)
BigDecimal.new(scaled.value % other.value, other.scale)
else
BigDecimal.new(@value % other.value, @scale)
end
end

def %(other : Int)
self % BigDecimal.new(other)
end

def /(other : BigDecimal) : BigDecimal
div other
end
Expand Down