[Tex/LaTex] How to check if the value of a parameter is a number

conditionalsmacros

I have a command with a parameter. I want to check if its value is a positive number and perform actions based on that.

\newcommand{\mycommand}[1]{
    \ifnum#1>0%
        %some actions
    \fi
}

But I receive errors when the value of the parameter is not a number, e.g.:

\mycommand{*}

How can I check if the value of #1 is a number?

Best Answer

Update:

Since it appears that the \IfInteger from the xtring package perceives blank strings as integers (the empty string {} is ok, but not { }), I have defined a modified macro \IsInteger which handles that case:

enter image description here

\documentclass{article}

\newcommand*{\IsInteger}[3]{%
    \IfStrEq{#1}{ }{%
        #3% is a blank string
    }{%
        \IfInteger{#1}{#2}{#3}%
    }%
}%
\usepackage{xstring}
\begin{document}
$2$ is \IsInteger{2}{an integer}{not an integer}\par
$2.0$ is \IsInteger{2.0}{an integer}{not an integer}

$-7$ is \IsInteger{-7}{an integer}{not an integer}\par
$-7.0$ is \IsInteger{-7.0}{an integer}{not an integer}

$2.1$ is \IsInteger{2.1}{an integer}{not an integer}\par
$-7.1$ is \IsInteger{-7.1}{an integer}{not an integer}

a is \IsInteger{a}{an integer}{not an integer}

Empty String is \IsInteger{}{an integer}{not an integer}\par
Blank String is \IsInteger{       }{an integer}{not an integer}
\end{document}

You can use IfInteger from the xstring package to test if it is an integer number:

enter image description here

There is also \IfDecimal which works similarly.

\documentclass{article}
\usepackage{xstring}
\begin{document}
2 is \IfInteger{2}{integer}{not an integer}

a is \IfInteger{a}{integer}{not an integer}
\end{document}