Skip to content

Commit 0211cd7

Browse files
chrisseatoneregon
authored andcommitted
Fix some rounding corner cases
1 parent ff28bfb commit 0211cd7

File tree

2 files changed

+26
-8
lines changed

2 files changed

+26
-8
lines changed

spec/ruby/core/integer/round_spec.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,12 +67,15 @@
6767
25.round(-1, half: :up).should eql(30)
6868
25.round(-1, half: :down).should eql(20)
6969
25.round(-1, half: :even).should eql(20)
70+
25.round(-1, half: nil).should eql(30)
7071
35.round(-1, half: :up).should eql(40)
7172
35.round(-1, half: :down).should eql(30)
7273
35.round(-1, half: :even).should eql(40)
74+
35.round(-1, half: nil).should eql(40)
7375
(-25).round(-1, half: :up).should eql(-30)
7476
(-25).round(-1, half: :down).should eql(-20)
7577
(-25).round(-1, half: :even).should eql(-20)
78+
(-25).round(-1, half: nil).should eql(-30)
7679
end
7780

7881
ruby_version_is "2.4"..."2.5" do
@@ -90,4 +93,9 @@
9093
35.round(1, half: :even).should eql(35)
9194
end
9295
end
96+
97+
it "raises ArgumentError for an unknown rounding mode" do
98+
lambda { 42.round(-1, half: :foo) }.should raise_error(ArgumentError, /invalid rounding mode: foo/)
99+
lambda { 42.round(1, half: :foo) }.should raise_error(ArgumentError, /invalid rounding mode: foo/)
100+
end
93101
end

src/main/ruby/truffleruby/core/integer.rb

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ def chr(enc=undefined)
161161
String.from_codepoint self, enc
162162
end
163163

164-
def round(ndigits=undefined, half: nil)
164+
def round(ndigits=undefined, half: :up)
165165
return self if undefined.equal? ndigits
166166

167167
if Float === ndigits && ndigits.infinite?
@@ -172,7 +172,12 @@ def round(ndigits=undefined, half: nil)
172172
Truffle::Type.check_int(ndigits)
173173

174174
if ndigits >= 0
175-
self
175+
case half
176+
when :up, nil, :down, :even
177+
self
178+
else
179+
raise ArgumentError, "invalid rounding mode: #{half}"
180+
end
176181
else
177182
ndigits = -ndigits
178183

@@ -185,12 +190,17 @@ def round(ndigits=undefined, half: nil)
185190

186191
if kind_of? Integer and f.kind_of? Integer
187192
x = self < 0 ? -self : self
188-
x = if (half == :down)
189-
x / f
190-
else # :up or nil
191-
(x + f / 2) / f
192-
end
193-
x = (x / 2) * 2 if half == :even
193+
case half
194+
when :up, nil
195+
x = (x + (f / 2)) / f
196+
when :down
197+
x = x / f
198+
when :even
199+
x = (x + (f / 2)) / f
200+
x = (x / 2) * 2
201+
else
202+
raise ArgumentError, "invalid rounding mode: #{half}"
203+
end
194204
x = x * f
195205
x = -x if self < 0
196206
return x

0 commit comments

Comments
 (0)