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.

\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
share|improve this question
add comment

2 Answers

up vote 9 down vote accepted

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}
share|improve this answer
    
Sorry, that did not solve the problem... –  Pygmalion Aug 16 '12 at 7:09
    
The code works for me (\axes{200} executes the true branch, as does \axes{160+40}, while \axes{190-20} does not). You'll need to be more specific than "did not solve the problem". –  Jake Aug 16 '12 at 7:19
    
@jake Now I figured out. The problem is that \anga is not integer, but real number...! So I can't use ifnum for real numbers? –  Pygmalion Aug 16 '12 at 7:29
1  
@Pygmalion No, you can't. You could have specified that at the beginning. I believe there's a solution by \ifdim\dimexpr but I'm not familiar with these things. –  tohecz Aug 16 '12 at 7:42
    
@LeoLiu Not directly relevant, but you don't need the \relax before <, as the \numexpr will be terminated 'safely' by the <. –  Joseph Wright Aug 16 '12 at 7:51
show 3 more comments

For floating points, there are approaches using \dimexpr, as tohecz says. However, for a truly general solution, I would use the LaTeX3 FPU

\documentclass{article}
\usepackage{expl3}
\ExplSyntaxOn
\cs_new:Npn \axes #1
  {
    \fp_compare:nNnT { abs (#1) } > { 180 }
      { blah ; }
  }
\ExplSyntaxOff
\begin{document}
\axes{200}; % fine
\def\anga{20.5}
\axes{180+\anga}; % fine
\end{document}
share|improve this answer
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.