, :
defmodule NumFmt do
def format(value, pos, round? \\ true)
def format(value, pos, _) when is_integer(value),
do: format(Integer.to_string(value), pos)
def format(value, pos, round?) when is_float(value),
do: format(Float
|> apply((if round?, do: :round, else: :floor), [value, pos])
|> Float.to_string, pos)
def format(value, 0, _) when is_binary(value),
do: with [i | _] <- String.split(value, "."), do: i
def format(value, pos, round?) when is_binary(value) do
case String.split(value, ".") do
[i] -> format(i <> ".0", pos, round?)
[i, f] -> [i, f
|> String.pad_trailing(pos, "0")
|> String.slice(0..pos - 1)] |> Enum.join(".")
end
end
end
IO.inspect NumFmt.format(123.101, 6), label: "123.101000"
IO.inspect NumFmt.format(123, 3), label: "123.000"
IO.inspect NumFmt.format(123.101, 1), label: "123.1"
IO.inspect NumFmt.format(123.000, 0), label: "123"