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 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 }
\]
share|improve this question
    
\ifnum\myNumericString<0? –  egreg Feb 4 '12 at 10:59

2 Answers 2

up vote 3 down vote accepted

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}

enter image description here

share|improve this answer

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

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.