Skip to content

Commit

Permalink
Adds Numbers.as_string helper
Browse files Browse the repository at this point in the history
  • Loading branch information
dkln committed Aug 20, 2024
1 parent 2069958 commit 5e827f7
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
34 changes: 34 additions & 0 deletions lib/wuunder_utils/numbers.ex
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,40 @@ defmodule WuunderUtils.Numbers do
end
end

@doc """
Tries to convert a number to a string. When the given value is already a binary, it tries to parse it and output it accordingly.
## Examples
iex> WuunderUtils.Numbers.as_string(13.37)
"13.37"
iex> WuunderUtils.Numbers.as_string(Decimal.new("13.37"))
"13.37"
iex> WuunderUtils.Numbers.as_string(1337)
"1337"
iex> WuunderUtils.Numbers.as_string("1337")
"1337.0"
iex> WuunderUtils.Numbers.as_string("1abc300")
"1.0"
"""
@spec as_string(any()) :: String.t() | nil
def as_string(value) when is_decimal(value), do: Decimal.to_string(value)
def as_string(value) when is_float(value), do: Float.to_string(value)
def as_string(value) when is_integer(value), do: Integer.to_string(value)

def as_string(value) when is_binary(value) do
value
|> parse_float()
|> as_string()
end

def as_string(nil), do: nil

@doc """
Adds two Decimal's together. Defaults back to 0.
Expand Down
2 changes: 1 addition & 1 deletion mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ defmodule WuunderUtils.MixProject do
start_permanent: Mix.env() == :prod,
test_coverage: [tool: ExCoveralls],
preferred_cli_env: [coveralls: :test, "coveralls.html": :test],
version: "0.8.0"
version: "0.8.1"
]
end

Expand Down

0 comments on commit 5e827f7

Please sign in to comment.