Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer

up vote 6 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
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
add comment

Your Answer

 
discard

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.