I'm working on an application in Erlang that has to deal with number formatting for several different currencies. There are many complexities to take in consideration, like currency symbols, where it goes (right or left), etc. But one aspect of this kind of formatting use to be straight forward in other programming languages but it's being hard in Erlang, which is the separators to use for thousands and decimal places.
For most of the English speaking countries (independent of the currency) the expected number format is:
9,999,999.99
For several other countries, like Germany and Brazil, the number format is different:
9.999.999,99
There are other variations, like the French variation, with spaces:
9 999 999,99
The problem is that I can't find a nice way to achieve these formats, starting from the floating point number. Sure the io_lib:format/2
can convert it to a string, but it seems to not offer any control over the symbols to use as decimal separator and doesn't output any separator for the thousands (which makes a workaround to "search-and-replace" impossible).
This is an example of what we have so far:
%% currency_l10n.erl
-module(currency_l10n).
-export([format/2]).
number_format(us, Value) ->
io_lib:format("~.2f", [Value]);
number_format(de, Value) ->
io_lib:format("~B,~2..0B", [trunc(Value), trunc(Value*100) rem 100]).
%% Examples on the Erlang REPL:
1> currency_l10n:number_format(us, 9999.99).
"9999.99"
2> currency_l10n:number_format(de, 9999.99).
"9999,99"
As you can see, already the workaround for the decimal separator is not exactly pretty and dealing with the delimiters for thousands won't be nicer. Is there anything we are missing here?