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:




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


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

\def\mytestvar{ mistake}

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


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


This results with the output:

Test 1 false (as expected)
Test 2 true (as expected)
! Missing number, treated as zero.
<to be read again> 
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?


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.

  • Fantastic! Thanks for the great tip, @MartinScharrer - wish I didn't have to wait 8 more minutes to accept :) Cheers! – sdaau Jun 10 '12 at 11:41
  • 3
    In case \mytestvar is empty I'd add \ifnum2=0\mytestvar\relax or something to avoid unexpected consequences. Furthermore, bad things happen if \mytestvar starts with 2 followed by text. Maybe it would be better to first test whether \mytestvar is numeric at all, compare Testing for number. – Stephan Lehmke Jun 10 '12 at 11:49
  • Thanks for the great link, @StephanLehmke - quite a nice collection of "isNum" type functions there; cheers! – sdaau Jun 10 '12 at 11:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.