File tree Expand file tree Collapse file tree 2 files changed +38
-0
lines changed Expand file tree Collapse file tree 2 files changed +38
-0
lines changed Original file line number Diff line number Diff line change @@ -127,4 +127,29 @@ defmodule Float do
127
127
end
128
128
end
129
129
130
+ @ doc """
131
+ Rounds a floating point value to an arbitrary number of fractional digits
132
+ (between 0 and 15) with an optional midpoint rounding mode (:up or :down,
133
+ defaults to :up).
134
+
135
+ ## Examples
136
+
137
+ iex> Float.round(5.5675, 3)
138
+ 5.568
139
+ iex> Float.round(5.5675, 3, :down)
140
+ 5.567
141
+ iex> Float.round(-5.5675, 3)
142
+ -5.567
143
+ iex> Float.round(-5.5675, 3, :down)
144
+ -5.568
145
+ """
146
+ @ spec round ( float , integer , atom | nil ) :: float
147
+ def round ( number , precision , midpoint_rounding // :up ) when is_float ( number ) and is_integer ( precision ) and precision in 0 .. 15 do
148
+ # Default to :up if anything but :down is provided for midpoint rounding mode
149
+ case midpoint_rounding do
150
+ :down -> Kernel . round ( Float . floor ( number * :math . pow ( 10 , precision ) ) ) / :math . pow ( 10 , precision )
151
+ _ -> Kernel . round ( Float . ceil ( number * :math . pow ( 10 , precision ) ) ) / :math . pow ( 10 , precision )
152
+ end
153
+ end
154
+
130
155
end
Original file line number Diff line number Diff line change @@ -57,4 +57,17 @@ defmodule FloatTest do
57
57
assert Float . ceil ( - 0.32453e-10 ) === 0
58
58
assert Float . ceil ( 1.32453e-10 ) === 1
59
59
end
60
+
61
+ test :round do
62
+ assert Float . round ( 5.5675 , 3 ) === 5.568
63
+ assert Float . round ( 5.5675 , 3 , :down ) === 5.567
64
+ assert Float . round ( 5.5 , 3 ) === 5.5
65
+ assert Float . round ( 5.5e-10 , 10 ) === 6.0e-10
66
+ assert Float . round ( 5.5e-10 , 10 , :down ) === 5.0e-10
67
+ assert Float . round ( 5.5e-10 , 8 ) === 1.0e-8
68
+ assert Float . round ( 5.5e-10 , 8 , :down ) === 0.0
69
+ assert Float . round ( 5.0 , 0 ) === 5.0
70
+ assert Float . round ( - 1.3456 , 3 ) === - 1.345
71
+ assert Float . round ( - 1.3456 , 3 , :down ) === - 1.346
72
+ end
60
73
end
You can’t perform that action at this time.
0 commit comments