8

I'm in the process of writing a command that outputs a certain text only if its argument is a nonzero number. I'd like to be able to write something like:

\newcommand{mycommand}[1]{
\if{#1 != 0}
Some text, because it's nonzero
\else
Some other text, because it's zero
\fi
}

\mycommand{0}
\mycommand{1}

And get the output:

Some other text, because it's zero
Some text, because it's nonzero

I'm running into trouble getting the conditional right, though - I'm not sure that LaTeX is treating #1 like an integer to be checked (or even if that's the right syntax for not-equals - I wasn't able to find a ton of information on integer conditionals). How might I go about writing this conditional?

  • 4
    You should end the lines with % otherwise you'll get additional spaces in your text. Try foo\mycommand{0}bar with the working code from Martin – user2478 Jan 31 '11 at 22:47
10

You can do it like this:

\newcommand{\mycommand}[1]{%
\ifnum0=#1\relax
  Some other text, because it's zero
\else
  Some text, because it's nonzero
\fi
}

Or with the ifthen package:

\ifthenelse{0=#1}{%
    Some other text, because it's zero
}{%
    Some text, because it's nonzero
}
5

For someone who might be looking to do this in ConTeXt, the equivalent solution is

\define[1]\mycommand%
  {\doifelse{#1}{0}
       {Some text, because it is zero}
       {Some other text, because it is not zero}}

See the wiki page on branching for more details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.