1

Is there a good way to format a minus number with zero padding in Erlang? The following works well for unsigned value, but for minus value, zero is padded before the sign.

io:format("~4..0B~n", [42]).
0042
ok

io:format("~4..0B~n", [-42]).
0-42
ok

What I have in mind is the following format.

(ruby)

1.9.2-p290 :004 > sprintf("%05d", -42)
"-0042"
1.9.2-p290 :005 > sprintf("%05d", 42)
"00042"

(python)

>>> "%05d" % -42
'-0042'
>>> "%05d" % 42
'00042'

I've referred to the following questions, but haven't been able to find one which talks about minus values.

How to format a number with padding in Erlang

Erlang: How to transform a decimale into a Hex string filled with zeros

Community
  • 1
  • 1
parroty
  • 1,385
  • 9
  • 12

1 Answers1

3

Currently there is no direct way of doing this in Erlang. The padding char is for the whole field and their is no way of padding just the actual value. The precision field is used for the base with which to print the integer. Using ~w does not help as the precision behaves the same way as the field width. I myself have trying to do this very recently and not come up with a simple solution.

EDIT: If you look here https://github.com/rvirding/luerl/blob/develop/src/luerl_string.erl#L156 there is a function format which does a C sprintf like formatted output. It is written for a Lua implementation and is probably more general than you need, but look at the function print_integer and print_float for the base handling. I have some better functions on the go which I should be pushing this evening.

rvirding
  • 20,848
  • 2
  • 37
  • 56