From 5e827f72b5367412aa7d8196b1f9177c3668891f Mon Sep 17 00:00:00 2001 From: Diederick Lawson Date: Tue, 20 Aug 2024 14:51:43 +0200 Subject: [PATCH] Adds Numbers.as_string helper --- lib/wuunder_utils/numbers.ex | 34 ++++++++++++++++++++++++++++++++++ mix.exs | 2 +- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/lib/wuunder_utils/numbers.ex b/lib/wuunder_utils/numbers.ex index 51819b7..54040c7 100644 --- a/lib/wuunder_utils/numbers.ex +++ b/lib/wuunder_utils/numbers.ex @@ -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. diff --git a/mix.exs b/mix.exs index 81b420f..6f04afe 100644 --- a/mix.exs +++ b/mix.exs @@ -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