# How does \if \else work at \DeclareDocumentCommand?

I made a command with DeclareDocumentCommand from the packet xparse, and I have had troubles. My problem is that the \ifmmode (if mathmode) and the else don't work correctly, because when I type $$\num{}[]$$, it shows the things that are in \ifmmode and \else.

Here is part of the code

\DeclareDocumentCommand{\num}{m o o}{
\ifmmode
\text{mathmode}
\IfValueT{#1}{\text{#1}}
\IfValueT{#2}{
\IfNoValueTF{#3}{
\,\text{#2}
}
}
\else
\text{textmode}
\IfValueT{#1}{#1}
\IfValueT{#2}{
\IfValueT{#3}{#2/#3}
%\, % Espacio
\IfNoValueTF{#3}{\ \text{#2}}
}
\fi
}

• Don't use \DeclareDocumentCommand; it would silently override existing commands; in particular \num is defined by siunitx. – egreg May 23 at 10:26
• And what command should I use? – El borito May 24 at 23:10
• \NewDocumentCommand is the right choice. – egreg May 24 at 23:10

You used \IfNoValueTF but only provided one branch where two were expected. You probably meant to use \IfNoValueT.

\documentclass{article}
\usepackage{amsmath}
\usepackage{xparse}
\NewDocumentCommand{\num}{m o o}{%
\ifmmode
\text{mathmode}%
\IfValueT{#1}{\text{#1}}%
\IfValueT{#2}{%
\IfNoValueT{#3}{% <<< T instead of TF
\,\text{#2}%
}%
}%
\else
\text{textmode}%
\IfValueT{#1}{#1}%
\IfValueT{#2}{%
\IfValueT{#3}{#2/#3}%
%\, % Espacio
\IfNoValueT{#3}{\ \text{#2}}% <<< T instead of TF
}%
\fi
}
\begin{document}
$\num{}[]$
\end{document}

• Thank you!! you are so great – El borito May 23 at 4:34
• The last two tests can be incorporated in a single \IfNoValueTF. Besides, it makes no sense to do \IfValueT{#1}, because it's a mandatory argument. – egreg May 23 at 10:38
• @egreg you are right – El borito May 24 at 22:48