# How to detect if the first non-space/non-tab character in a string is '-' (minus)?

I have a macro \myNumericString that expands to a string of numbers, with the possibility to present a minus sign as a first non-space character. How can I construct a macro:

\isNegative{\myNumericString}{ true }{ false }


in order to make decisions on how to treat \myNumericString in successive typesetting steps? Here's a simple case of usage:

$4 \times \isNegative{\myNumericString}{ ( \myNumericString ) }{ \myNumericString }$

-
\ifnum\myNumericString<0? –  egreg Feb 4 '12 at 10:59

If you are sure that \myNumericString is what TeX expects as a <number>, then

\makeatletter
\newcommand{\isNegative}[1]{%
\ifnum#1<0
\expandafter\@firstoftwo
\else
\expandafter\@secondoftwo
\fi}
\makeatother


If \myNumericString possibly has a decimal part, you can use

\ifdim#1pt<0pt


instead (the integer part cannot exceed 16383).

A better definition that only examines the first token in the expansion of \myNumericString is

\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\isNegative}{m}
{
\exp_args:Nx \str_if_eq:nnTF { \tl_head:f { #1 } } { - }
}
\ExplSyntaxOff


Here's an example document

\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\isNegative}{m}
{
\exp_args:Nx \str_if_eq:nnTF { \tl_head:f { #1 } } { - }
}
\ExplSyntaxOff

\begin{document}
\def\myNumericString{123.456}
$4\times\isNegative{\myNumericString}{(\myNumericString)}{\myNumericString}$

\def\myNumericString{-123.456}
$4\times\isNegative{\myNumericString}{(\myNumericString)}{\myNumericString}$
\end{document}


-

if you need it for all arguments:

\documentclass{article}
\makeatletter
\newcommand\isNegative[1]{\expandafter\is@Negative#1\@nil}
\def\is@Negative{\@ifnextchar-{\@negative}{\@positive}}
\def\@negative-#1\@nil{#1 starts with a minus}
\def\@positive#1\@nil{#1 starts not with a minus}
\makeatother
\begin{document}
\def\myNumericString{123.456}
\isNegative{\myNumericString}

\def\myNumericString{-123.456}
\isNegative{\myNumericString}

\isNegative{     -foo}
\end{document}

-
+1 This is a nice solution as well, but here \isNegative doesn't fit with the macro proposed in the answer. –  agodemar Feb 5 '12 at 9:30