Skip to content

Commit d624ceb

Browse files
committed
Add floor and ceil functions to Float
1 parent cf0dd31 commit d624ceb

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

lib/elixir/lib/float.ex

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,4 +80,49 @@ defmodule Float do
8080
result
8181
end
8282
end
83+
84+
@doc """
85+
Round a float to the largest integer less than or equal to `num`
86+
87+
## Examples
88+
iex> Float.floor(34)
89+
34
90+
iex> Float.floor(34.25)
91+
34
92+
iex> Float.floor(-56.5)
93+
-57
94+
95+
"""
96+
@spec floor(float | integer) :: integer
97+
def floor(num) when is_integer(num), do: num
98+
def floor(num) when is_float(num) do
99+
truncated = :erlang.trunc(num)
100+
case :erlang.abs(num - truncated) do
101+
x when x > 0 and num < 0 -> truncated - 1
102+
x -> truncated
103+
end
104+
end
105+
106+
@doc """
107+
Round a float to the largest integer greater than or equal to `num`
108+
109+
## Examples
110+
iex> Float.ceil(34)
111+
34
112+
iex> Float.ceil(34.25)
113+
35
114+
iex> Float.ceil(-56.5)
115+
-56
116+
117+
"""
118+
@spec ceil(float | integer) :: integer
119+
def ceil(num) when is_integer(num), do: num
120+
def ceil(num) when is_float(num) do
121+
truncated = :erlang.trunc(num)
122+
case :erlang.abs(num - truncated) do
123+
x when x > 0 and num > 0 -> truncated + 1
124+
x -> truncated
125+
end
126+
end
127+
83128
end

lib/elixir/test/elixir/float_test.exs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,36 @@ defmodule FloatTest do
2525
assert Float.parse("++1.2") === :error
2626
assert Float.parse("pi") === :error
2727
end
28+
29+
test :floor do
30+
assert Float.floor(12) === 12
31+
assert Float.floor(-12) === -12
32+
assert Float.floor(12.524235) === 12
33+
assert Float.floor(-12.5) === -13
34+
assert Float.floor(-12.524235) === -13
35+
assert Float.floor(7.5e3) === 7500
36+
assert Float.floor(7.5432e3) === 7543
37+
assert Float.floor(7.5e-3) === 0
38+
assert Float.floor(-12.32453e4) === -123246
39+
assert Float.floor(-12.32453e-10) === -1
40+
assert Float.floor(0.32453e-10) === 0
41+
assert Float.floor(-0.32453e-10) === -1
42+
assert Float.floor(1.32453e-10) === 0
43+
end
44+
45+
test :ceil do
46+
assert Float.ceil(12) === 12
47+
assert Float.ceil(-12) === -12
48+
assert Float.ceil(12.524235) === 13
49+
assert Float.ceil(-12.5) === -12
50+
assert Float.ceil(-12.524235) === -12
51+
assert Float.ceil(7.5e3) === 7500
52+
assert Float.ceil(7.5432e3) === 7544
53+
assert Float.ceil(7.5e-3) === 1
54+
assert Float.ceil(-12.32453e4) === -123245
55+
assert Float.ceil(-12.32453e-10) === 0
56+
assert Float.ceil(0.32453e-10) === 1
57+
assert Float.ceil(-0.32453e-10) === 0
58+
assert Float.ceil(1.32453e-10) === 1
59+
end
2860
end

0 commit comments

Comments
 (0)