Skip to content

Commit 6697100

Browse files
author
José Valim
committed
Merge pull request #1989 from chaslemley/fix_float_round_error
fix issue with Float.round/3 (midpoint_rounding)
2 parents 4fae777 + 94812b4 commit 6697100

File tree

2 files changed

+10
-19
lines changed

2 files changed

+10
-19
lines changed

lib/elixir/lib/float.ex

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -141,27 +141,22 @@ defmodule Float do
141141

142142
@doc """
143143
Rounds a floating point value to an arbitrary number of fractional digits
144-
(between 0 and 15) with an optional midpoint rounding mode (:up or :down,
145-
defaults to :up).
144+
(between 0 and 15).
146145
147146
## Examples
148147
148+
iex> Float.round(5.5674, 3)
149+
5.567
149150
iex> Float.round(5.5675, 3)
150151
5.568
151-
iex> Float.round(5.5675, 3, :down)
152-
5.567
153-
iex> Float.round(-5.5675, 3)
152+
iex> Float.round(-5.5674, 3)
154153
-5.567
155-
iex> Float.round(-5.5675, 3, :down)
154+
iex> Float.round(-5.5675, 3)
156155
-5.568
157156
"""
158-
@spec round(float, integer, atom | nil) :: float
159-
def round(number, precision, midpoint_rounding // :up) when is_float(number) and is_integer(precision) and precision in 0..15 do
160-
# Default to :up if anything but :down is provided for midpoint rounding mode
161-
case midpoint_rounding do
162-
:down -> Kernel.round(Float.floor(number * :math.pow(10, precision))) / :math.pow(10, precision)
163-
_ -> Kernel.round(Float.ceil(number * :math.pow(10, precision))) / :math.pow(10, precision)
164-
end
157+
@spec round(float, integer) :: float
158+
def round(number, precision) when is_float(number) and is_integer(precision) and precision in 0..15 do
159+
Kernel.round(number * :math.pow(10, precision)) / :math.pow(10, precision)
165160
end
166161

167162
end

lib/elixir/test/elixir/float_test.exs

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -61,14 +61,10 @@ defmodule FloatTest do
6161

6262
test :round do
6363
assert Float.round(5.5675, 3) === 5.568
64-
assert Float.round(5.5675, 3, :down) === 5.567
64+
assert Float.round(-5.5674, 3) === -5.567
6565
assert Float.round(5.5, 3) === 5.5
6666
assert Float.round(5.5e-10, 10) === 6.0e-10
67-
assert Float.round(5.5e-10, 10, :down) === 5.0e-10
68-
assert Float.round(5.5e-10, 8) === 1.0e-8
69-
assert Float.round(5.5e-10, 8, :down) === 0.0
67+
assert Float.round(5.5e-10, 8) === 0.0
7068
assert Float.round(5.0, 0) === 5.0
71-
assert Float.round(-1.3456, 3) === -1.345
72-
assert Float.round(-1.3456, 3, :down) === -1.346
7369
end
7470
end

0 commit comments

Comments
 (0)