[Tex/LaTex] Converting strings to counts

countersmacros

I'm reading in a number (as text) from the aux file and I want to do a numerical test (\ifnum) on it. I can to it using \setcounter and \value, but I really don't want to create a counter just to do a lousy test. Is there a simpler way?

Using pgfmath is not by any stretch of the imagination simpler.

\documentclass{article}
\newcount\test
\newcounter{test}
\begin{document}

\def\temp{1}

\setcounter{test}{\temp}
\ifnum\value{test}>0 Yea!
\else Boo!
\fi

\test=\temp
\ifnum\test>0 Yea!
\else Boo!
\fi

\end{document}

In retrospect, my mistake is obvious. In an expression like

\test=1

the end-of-line terminates both adding digits and conversion of "1" to a count. But with

\test=\temp

the end-of-line is consumed terminating the macro name. I suspect that the final expansion of this is actually

\test=1 Boo!

which is legal but too late. The simplest solution

\test=\temp\relax

uses \relax to force the expression to completion.

Best Answer

As I indicated in my comment, you can dispense with the counters. Just use the \def as an argument. If you need a more complex calculation, you can use \numexpr, as in my 2nd example.

\documentclass{article}
\begin{document}

\def\temp{1}
\def\X{2}

\ifnum\temp>0 Yea!
\else Boo!
\fi

\ifnum\numexpr\temp-\X\relax>0 Yea!
\else Boo!
\fi

\end{document}

enter image description here


To follow up with the OP's comment about difficulty of mixing tokens and counters, I will post this MWE that works with that mix:

\documentclass{article}
\newcounter{mycount}
\setcounter{mycount}{0}
\begin{document}
\def\temp{1}
\ifnum\value{mycount}>\temp Yea!
\else Boo!
\fi
\end{document}
Related Question