TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 7 down vote accepted

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.

share|improve this answer
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
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 posting your answer, you agree to the privacy policy and terms of service.

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