5
$\begingroup$

I want to format all numbers from 1 to 50 so that they are all 2 digits long.

desiredOutput={01,02,...,49,50}

Digging through the documentation the NumberForm function looked promising.

After trying many options and parameters I so far cannot achieve my desired output.

Attempt:

format = NumberForm[#, 1, NumberPadding -> {"0", ""}] &;
format/@Range[50]

enter image description here

I notice that NumberForm can "adapt" to integers of different lengths for numbers of length 3.

enter image description here

$\endgroup$
2
$\begingroup$

It's not exactly a number formatting, but this might be of some help anyway:

format = StringPadLeft[ToString@#, 2, "0"] &;
format /@ Range[50]

{"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50"}

Clearly, the Head of the list elements is not NumberForm anymore, but String, which might be useful for some applications (plot ticks for example) but not for others...

| improve this answer | |
$\endgroup$
  • 4
    $\begingroup$ IntegerString[#, 10, 2] & would be somewhat more direct. Note that both of these methods will truncate integers larger than 2 digits. $\endgroup$ – LegionMammal978 Jan 21 at 0:46
5
$\begingroup$

Here is way to do it that also handles negative integers as well as non-negative ones.

Clear[format]
format[n_Integer] /; -1 < n < 10 := NumberForm[n, 0, NumberFormat -> (Row[{"0", #1}] &)]
format[n_Integer] /; -10 < n < 0 := NumberForm[-n, 0, NumberFormat -> (Row[{"-0", #1}] &)]
format[n_Integer] := n

Test

format /@ Range[-12, 12, 2]

{-12, -10, -08, -06, -04, -02, 00, 02, 04, 06, 08, 10, 12}

| improve this answer | |
$\endgroup$
2
$\begingroup$
If[# < 10, "0" <> ToString@#, ToString@#] & /@ Range[50]

or,in your way

If[# < 10, NumberForm[#, 1, NumberPadding -> {"0", ""}], #] & /@ Range[50]
| improve this answer | |
$\endgroup$
2
$\begingroup$
g[x_] := If[ 0 < x < 10, NumberForm[x , NumberPadding -> {"0", ""}], x]
g/@ list

in alternative, since my answer is similar to what wuyudi has proposed, you can use patterns with appropriate conditions

Range[50] /. 
 x_ /; 0 < x < 10 -> NumberForm[x , NumberPadding -> {"0", ""}]
| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.