[Tex/LaTex] How to convert a one digit number to a two digit number


I have a table that represents a timetable for bus, so each cell contains time of departure as hour followed by minute, both as two digits, but sometimes I don't have two digits,just one so I have to switch eg. from 12 4 -> 12 04.
How is it possible?

Best Answer

You can define a macro as follows:

   \ifnum#1<10 0#1\else #1\fi

\twodigits{12}  % 12
\twodigits{4}   % 04
\twodigits{123} % 123

This macro is fully expandable.

If you also want to cut trailing zeros you can use:

   \ifnum#1<10 0\number#1 \else #1\fi

\twodigits{004} % 04

If you want to change a tabular cell from 12 4 to 12 04 without adding explicit macros you can use the collcell package to collect the cell content and feed it to a macro which splits the numbers by the space:

% preamble:
\def\formatdatei#1 #2\relax{%
   \twodigits{#1} \twodigits{#2}%


% later
   Bus date  & 12 4 \\

If you post a real usage example I can help me with more specific macros.

Related Question