[Tex/LaTex] Passing argument to \ifnum

macrostex-core

\ifnum works fine it it's got two straight numbers. However, when calculation is involved, I get bunch of ! Missing = inserted for \ifnum. errors. Is there any way to solve that problem?

\newcommand{\axes}[1]{
\ifnum\ifnum#1>180 1\else\ifnum#1>-180 0\else1\fi\fi =1
  blah;
\fi}

\axes{200}; % fine
\def\anga{20.5};
\axes{180+\anga}; % not fine

Best Answer

You can't use arithmetic expression in TeX primitives. However, since modern TeX all support eTeX extensions, you can use \numexpr to do the calculation:

\newcommand\axes[1]{%
\ifnum\ifnum\numexpr#1\relax>180 1\else\ifnum\numexpr#1\relax>-180 0\else1\fi\fi =1
  blah;
\fi}

\axes{200}; % fine
\def\anga{20}
\axes{180+\anga}; % fine

If you use pgf or tikz to draw axis (why not?), you can use pgfmath for length arithmetic.

\documentclass{article}
\usepackage{tikz} % or pgf

\begin{document}

\newcommand\axes[1]{%
  \pgfmathparse{
    ifthenelse(abs(#1) > 180, "out", "in")}%
  \pgfmathresult
}

\axes{200.3}; % out

\def\anga{-20.4}
\axes{180+\anga}; % in

\axes{-5.5}; % out

\end{document}
Related Question