improvement: added round/1 and round/2 to expressions

This commit is contained in:
Zach Daniel 2023-07-27 11:49:02 -04:00
parent 7bbc7ba4e3
commit 1871e19fa9
3 changed files with 31 additions and 0 deletions

View file

@ -47,6 +47,8 @@ The following functions are built in:
- `string_split/2` | As above, but with a specific delimiter
- `string_split/3` | As above, but with options. See the function for the available options.
- `at/2` | Get an element from a list, i.e `at(list, 1)`
- `round/1` | Round a float, decimal or int to 0 precision, i.e `round(num)`
- `round/2` | Round a float, decimal or int to the provided precision or less, i.e `round(1.1234, 3) == 1.1234` and `round(1.12, 3) == 1.12`
## Sub-expressions

View file

@ -29,6 +29,7 @@ defmodule Ash.Filter do
Length,
Minus,
Now,
Round,
StringJoin,
StringSplit,
Today,
@ -61,6 +62,7 @@ defmodule Ash.Filter do
Length,
Minus,
Now,
Round,
Today,
Type,
StringJoin,

View file

@ -0,0 +1,27 @@
defmodule Ash.Query.Function.Round do
@moduledoc """
Rounds a float, decimal or integer to the given number of points
"""
use Ash.Query.Function, name: :round
def args,
do: [
[:float, :integer],
[:decimal, :integer],
[:integer, :integer],
[:float],
[:decimal],
[:integer]
]
def evaluate(%{arguments: [num]} = round), do: evaluate(%{round | arguments: [num, 0]})
def evaluate(%{arguments: [num, _]}) when is_integer(num), do: {:known, num}
def evaluate(%{arguments: [num, precision]}) when is_float(num),
do: {:known, Float.round(num, precision)}
def evaluate(%{arguments: [num, precision]}) do
{:known, num |> Decimal.round(precision) |> Decimal.normalize()}
end
end