6

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

Conor
  • 7,449
  • 1
  • 22
  • 46

4 Answers4

6

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}

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
2
If[# < 10, "0" <> ToString@#, ToString@#] & /@ Range[50]

or,in your way

If[# < 10, NumberForm[#, 1, NumberPadding -> {"0", ""}], #] & /@ Range[50]
AsukaMinato
  • 9,758
  • 1
  • 14
  • 40
2

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...

Fraccalo
  • 6,057
  • 13
  • 28
  • 4
    IntegerString[#, 10, 2] & would be somewhat more direct. Note that both of these methods will truncate integers larger than 2 digits. – LegionMammal978 Jan 21 '20 at 00:46
2
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", ""}]
Alucard
  • 2,639
  • 13
  • 22