5

Code

\documentclass{article}
\newcommand*\test[2]{#1\textsuperscript{#2}}
\begin{document}
The player ended as no.~\test{1}{} and her friend came in \test{2}{nd}.
\end{document}

Output

output

Question

How can I change the \test command so that I'm abel to switch between one or two arguments?

(I would like to be abel to write \test{1} instead of \test{1}{}.)

3 Answers3

8

With xparse the feature can be done easily with the g optional argumen t specifier, but optional arguments should be done with [...], i.e. use o rather, in my point of view!

\documentclass{article}
\usepackage{xparse}


\NewDocumentCommand{\test}{mg}{#1\IfValueT{#2}{\textsuperscript{#2}}}
\begin{document}
The player ended as no.~\test{1} and her friend came as \test{2}{nd}.
\end{document}
3

I'd suggest an alternative interface using * (say):

enter image description here

\documentclass{article}

\usepackage{fmtcount}

\makeatletter
\newcommand{\@test}[1]{#1}
\newcommand{\@@test}[1]{\ordinalnum{#1}}
\newcommand{\test}{\@ifstar\@test\@@test}
\makeatother

\begin{document}

\test{1} \test*{1}

\test{2} \test*{2}

\test{11} \test{12} \test{21}
\end{document}

The above command definition is also possible using xparse:

\usepackage{xparse}
\NewDocumentCommand{\test}{s m}
  {\IfBooleanTF{#1}{#2}{\ordinalnum{#2}}}
Werner
  • 603,163
0
\documentclass[a4paper]{article}
\newcommand\test[2][]{#2\ifx\relax#1\relax\else\textsuperscript{#1}\fi}
\begin{document}
The player ended as no.~\test{1} and her friend came ind \test[nd]{2}.
\end{document}