13

I am using the etoolbox package to check some variables. I can use \ifnumless{a}{b}{True}{False} to check if "a" is less than "b" and output "True" if true and "False" if false". How can I check if two conditionals are met though? E.g.:

IF a < b AND x > 100
DO "True"
ELSE "False"
3
  • 3
    \ifnumless{a}{b}{\ifnumgreater{x}{100}{True}{False}}{}
    – Werner
    Commented Dec 6, 2011 at 23:32
  • Does this mean I end up with two "False"'s?
    – Village
    Commented Dec 6, 2011 at 23:34
  • @Werner needs another False in his code (between the final {}). But you will end up with only 1 "False". Since the evaluation can always only end up in one branch. I think that it's a perfectly acceptable answer otherwise and Werner should add it. Commented Dec 7, 2011 at 10:21

2 Answers 2

24

You can use the logical combination and and or in the test \ifboolexpr

\ifboolexpr{%
    test {\ifnumless{a}{b}} 
    and
    test{\ifnumgreater{x}{100}}
   }{YES}{NO}

For more details see the documentation (section 3.6.5).


I want to show an example.

\documentclass{article}
\usepackage{etoolbox}
\newcounter{a}\newcounter{b}\newcounter{x}
\newrobustcmd*\setabx[3]{%
  \setcounter{a}{#1}\setcounter{b}{#2}\setcounter{x}{#3}%
}

\newrobustcmd*\iftwocont{%
  \ifboolexpr{%
    test {\ifnumless{\value{a}}{\value{b}}} 
    and
    test{\ifnumgreater{\value{x}}{100}}%
  }%
}
\begin{document}
\setabx{1}{1}{1}
\iftwocont{$a<b$ and $x>100$}{The logical combination is false}

\setabx{5}{10}{300}
\iftwocont{$a<b$ and $x>100$}{The logical combination is false}
\end{document}

Result:

The logical combination is false
a < b and x > 100
2
  • Have you ever looked in the trace log of \ifboolexpr? :) It's plentiful even for simple tests. If the conditions aren't more than two, I will suggest a direct test instead.
    – Ahmed Musa
    Commented Dec 7, 2011 at 2:15
  • 2
    @AhmedMusa: ifboolexpr allows the logical combination required by the OP. Commented Dec 7, 2011 at 8:54
1

The following takes less than 1% of the runtime used by \ifboolexpr and it does arithmetic. It can be changed to also do real numbers.

\documentclass{article}
\usepackage{catoptions}
\makeatletter
\def\numtest#1and#2#{%
  \ifnum\numexpr\cpt@numlt\cpt@numgt\cpt@numeq#1%
    \cpt@removetonnil<=>\cpt@nnil\relax
    \ifnum\numexpr\cpt@numlt\cpt@numgt\cpt@numeq#2%
      \cpt@removetonnil<=>\cpt@nnil\relax
      \expandafter\expandafter\expandafter\@firstoftwo
    \else
      \expandafter\expandafter\expandafter\@secondoftwo
    \fi
  \else
    \expandafter\@secondoftwo
  \fi
}
\makeatother

\numtest 1+2<3+2 and 4+3>2+3{true}{false}
\numtest 1+2<3+2 and 2+3>2+3{true}{false}
\numtest 1+2+4>3+2 and 2+3+4=2+3+5+3{true}{false}
1
  • 8
    You were able to calculate the runtime... and it was less than 1%? Really?
    – Werner
    Commented Dec 9, 2011 at 5:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .