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.

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?

share|improve this question
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 –  Herbert Jan 31 '11 at 22:47
    
Thanks, Herbert! –  Tim Jan 31 '11 at 23:09
add comment

2 Answers

up vote 9 down vote accepted

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
}
share|improve this answer
add comment

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.

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.