12

I have defined a new counter that keeps increasing each time I call the macro that's using it. How can I print the counter value minus one? Something like \value{\theCounter-1} but formatted for text?

MWE

\documentclass{article}
\usepackage{parskip}
\newcounter{myCount}
\setcounter{myCount}{1}
\newcommand\newSec[1]{\par\underline{\textsc{newSec}~\themyCount}\hspace{0.5em}{\footnotesize(#1~number)}\stepcounter{myCount}\par}

\begin{document}
    \newSec{2}
    Some text

    \newSec{5}
    Here I refer to the counter used before it was incremented: \themyCount. Should print 2. 
\end{document}
  • 1
    Use \setcounter{myCount}{0} and move the set counter \par\stepcounter{myCount} before underline. – Sigur Nov 4 '14 at 12:43
  • why aren't you using any of the latex machinery for section or list item headings? this looks sort of like a heading but you can't \label it, you may get a page break between the heading and the text and everything else the section heading code takes care of isn't taken care of. – David Carlisle Nov 4 '14 at 12:52
  • It was an emergency solution to using the exam class. Good thought about incrementing the counter first. Solves it! – Holene Nov 4 '14 at 12:53
15
 \the\numexpr\value{counter}-1\relax

should do what is asked in the question but you don't seem to need this, it is normal to advance the counter before using it, then its value in a section will be the value used in that sections heading, and you don't need to subtract.

  • Error: Illegal unit of measure (pt inserted) ...print 2. \the\dimexpr\value{myCount}\relax Why's that? – Holene Nov 4 '14 at 13:05
  • 2
    @Holene because you used what I wrote not what I meant to write (numexpr not dimexpr sorry) – David Carlisle Nov 4 '14 at 13:19
  • If I only want the actual value without increasing it, it is okay to just remove the "-1"? – Joel Duscha May 24 '16 at 8:47
  • 1
    @JoelDuscha yes but \thecounter would be more normal in that case (that's the specified print form) – David Carlisle May 24 '16 at 8:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.