Skip to content

Commit

Permalink
Showing 3 changed files with 51 additions and 2 deletions.
38 changes: 38 additions & 0 deletions spec/std/float_spec.cr
Original file line number Diff line number Diff line change
@@ -82,6 +82,44 @@ describe "Float" do
assert { 1.0.fdiv(0).should eq 1.0/0.0 }
end

describe "divmod" do
assert { 1.2.divmod(0.3)[0].should eq(4) }
assert { 1.2.divmod(0.3)[1].should be_close(0.0, 0.00001) }

assert { 1.3.divmod(0.3)[0].should eq(4) }
assert { 1.3.divmod(0.3)[1].should be_close(0.1, 0.00001) }

assert { 1.4.divmod(0.3)[0].should eq(4) }
assert { 1.4.divmod(0.3)[1].should be_close(0.2, 0.00001) }

assert { -1.2.divmod(0.3)[0].should eq(-4) }
assert { -1.2.divmod(0.3)[1].should be_close(0.0, 0.00001) }

assert { -1.3.divmod(0.3)[0].should eq(-5) }
assert { -1.3.divmod(0.3)[1].should be_close(0.2, 0.00001) }

assert { -1.4.divmod(0.3)[0].should eq(-5) }
assert { -1.4.divmod(0.3)[1].should be_close(0.1, 0.00001) }

assert { 1.2.divmod(-0.3)[0].should eq(-4) }
assert { 1.2.divmod(-0.3)[1].should be_close(0.0, 0.00001) }

assert { 1.3.divmod(-0.3)[0].should eq(-5) }
assert { 1.3.divmod(-0.3)[1].should be_close(-0.2, 0.00001) }

assert { 1.4.divmod(-0.3)[0].should eq(-5) }
assert { 1.4.divmod(-0.3)[1].should be_close(-0.1, 0.00001) }

assert { -1.2.divmod(-0.3)[0].should eq(4) }
assert { -1.2.divmod(-0.3)[1].should be_close(0.0, 0.00001) }

assert { -1.3.divmod(-0.3)[0].should eq(4) }
assert { -1.3.divmod(-0.3)[1].should be_close(-0.1, 0.00001) }

assert { -1.4.divmod(-0.3)[0].should eq(4) }
assert { -1.4.divmod(-0.3)[1].should be_close(-0.2, 0.00001) }
end

describe "to_s" do
it "does to_s for f64" do
12.34.to_s.should eq("12.34")
11 changes: 11 additions & 0 deletions spec/std/number_spec.cr
Original file line number Diff line number Diff line change
@@ -103,9 +103,20 @@ describe "Number" do
end

it "divides and calculs the modulo" do
11.divmod(3).should eq({3, 2})
11.divmod(-3).should eq({-4, -1})

10.divmod(2).should eq({5, 0})
11.divmod(2).should eq({5, 1})

10.divmod(-2).should eq({-5, 0})
11.divmod(-2).should eq({-6, -1})

-10.divmod(2).should eq({-5, 0})
-11.divmod(2).should eq({-6, 1})

-10.divmod(-2).should eq({5, 0})
-11.divmod(-2).should eq({5, -1})
end

it "compare the numbers" do
4 changes: 2 additions & 2 deletions src/number.cr
Original file line number Diff line number Diff line change
@@ -155,10 +155,10 @@ struct Number
#
# ```
# 11.divmod(3) # => {3, 2}
# 11.divmod(-3) # => {-3, 2}
# 11.divmod(-3) # => {-4, 1}
# ```
def divmod(number)
{self / number, self % number}
{(self / number).floor, self % number}
end

# Implements the comparison operator.

0 comments on commit ae551e9

Please sign in to comment.