[Tex/LaTex] Handling \ifnum’s “! Missing number, treated as zero.”

comparisonconditionalstex-core

Let's say I have a variable, which may – or may NOT – be a number; how can I handle the cases when it isn't a number, without crashing with "! Missing number, treated as zero." ?

In practical terms, consider the following MWE:

\documentclass{book}

\begin{document}

\def\mytestvar{4}

\ifnum\mytestvar=2 %
  \typeout{Test 1 true} %
\else %
  \typeout{Test 1 false (as expected)} %
\fi

\def\mytestvar{2}

\ifnum\mytestvar=2 %
  \typeout{Test 2 true (as expected)} %
\else %
  \typeout{Test 2 false} %
\fi

\def\mytestvar{ mistake}

\ifnum\mytestvar=2 %
  \typeout{Test 3 true} %
\else %
  \typeout{Test 3 false (as expected)} %
\fi

\def\mytestvar{2}

\ifnum\mytestvar=2 %
  \typeout{Test 4 true (as expected)} %
\else %
  \typeout{Test 4 false} %
\fi


\end{document}

This results with the output:

Test 1 false (as expected)
Test 2 true (as expected)
! Missing number, treated as zero.
<to be read again> 
                   m
l.23 \ifnum\mytestvar
                     =2 %
?  

How can I make Test 3 pass as false (instead of crash), so that Test 4 can perform as well in the same run? Hopefully, by not including any additional packages?

Best Answer

You can use \ifnum2=0\mytestvar. If \mytestvar expands to a number the leading 0 doesn't matter, but if it isn't a number there is at least some number there, which also triggers the false branch.

Related Question