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

conversionnumberingstrings

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:

\newcommand\twodigits[1]{%
   \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:

\newcommand\twodigits[1]{%
   \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:
\newcommand\formatdate[1]{\formatdatei#1\relax}
\def\formatdatei#1 #2\relax{%
   \twodigits{#1} \twodigits{#2}%
}

\usepackage{collcell}

% later
\begin{tabular}{l>{\collectcell\formatdate}l<{\endcollectcell}}
   Bus date  & 12 4 \\
\end{tabular}

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

Related Question