Skip to content

Instantly share code, notes, and snippets.

@perilbrain
Last active August 28, 2015 16:53
Show Gist options
  • Save perilbrain/62726f080e640e9b29ae to your computer and use it in GitHub Desktop.
Save perilbrain/62726f080e640e9b29ae to your computer and use it in GitHub Desktop.
Modified Version price.ex
defmodule X do
def format(number) when is_integer(number), do: number |> to_string |> format
def format(amount) when is_binary(amount) do
formatted_amount =
amount
|> String.replace(~r/\D/, "")
|> String.replace(~r/^0*(\d+)(\d{2})$/, "\\1,\\2")
|> pad
|> String.split( ",", parts: 2)
|> concat_format
"€ " <> formatted_amount
end
def amount_to_cents(amount) do
case Integer.parse(amount) do
{number,""} -> number * 100
{_,_} ->
{number, _} = amount |> String.replace(~r/\D/, "") |> Integer.parse
number
end
end
defp pad(""), do: "0,00"
defp pad(centified) when byte_size(centified) == 1, do: "0,0" <> centified
defp pad(centified) when byte_size(centified) == 2, do: "0," <> centified
defp pad(centified), do: centified
defp concat_format([x , "00"]), do: concat_format([x, "-"])
defp concat_format([x, y]), do: set_separators(x) <> "," <> y
defp set_separators(europart) do
f = fn
(r, []) -> [[r]]
(r, [h|acc]) when length(h) < 3 -> [[r|h]|acc]
(r, [h|acc]) -> [[r],h|acc]
end
List.foldr(europart |> to_char_list, [], f) |> :string.join('.') |> to_string
end
def test do
keylist = [
{"€ 0,-", ""},
{"€ 0,-", "0000"},
{"€ 1.234.567,89", "123456,789"},
{"€ 1.345,90", "001we345fs90"},
{"€ 0,01", "1"},
{"€ 0,12", "12"},
{"€ 1,23", "12.3"},
{"€ 12,34", "12.34"},
{"€ 123,45", "123,45"},
{"€ 1.234,56", "1234,56"},
{"€ 12.345,67", "12345.67"},
{"€ 123.456,78", "123456,78"},
{"€ 1.234.567,89", "1234567.89"},
{"€ 12.345.678,90", "12345678,90"},
{"€ 1,-", "1.00"},
{"€ 1,-", "1,00"}
]
:lists.foreach(
fn ({f, i}) ->
calc = format(i)
result = f == calc
IO.puts "#{i} -> #{f} == (#{calc}) : #{result} "
end,
keylist
)
end
end
@perilbrain
Copy link
Author

Additional test cases:-

iex(1)> X.format("1")
"€ 0,01"
iex(2)> X.format("")
"€ 0,00"
iex(3)> X.format(101)
"€ 1,01"
iex(4)> X.format(1)
"€ 0,01"
iex(5)> X.format(0)
"€ 0,-"

iex(1)> X.format("1,00")
"€ 1,-"
iex(2)> X.format("1, 00")
"€ 1,-"
iex(3)> X.format("12345678,90")
"€ 12.345.678,90"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment