21

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}
Holene
  • 6,920
  • 1
    Use \setcounter{myCount}{0} and move the set counter \par\stepcounter{myCount} before underline. – Sigur Nov 04 '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 04 '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 04 '14 at 12:53

1 Answers1

31
 \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.

David Carlisle
  • 757,742
  • Error: Illegal unit of measure (pt inserted) ...print 2. \the\dimexpr\value{myCount}\relax Why's that? – Holene Nov 04 '14 at 13:05
  • 3
    @Holene because you used what I wrote not what I meant to write (numexpr not dimexpr sorry) – David Carlisle Nov 04 '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 08: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 08:53
  • @DavidCarlisle Any hints why this solution does not work in this context: \tikzset{myset/.style={row #1 column 1/.style={execute at begin node=Week \space \the\numexpr\value{\pgfmatrixcurrentrow}-1}}} . Folks: I don't think it make sense to ask this as another question so I'm posting as a comment but if I'm wrong please let me know. – Sergio Parreiras Jun 04 '22 at 23:27
  • 1
    Please don't ask questions as comments on old answers, but does \pgfmatrixcurrentrow expand to the name of a counter? I suspect it does not, in which case it is unrelated to the code here. @SergioParreiras – David Carlisle Jun 04 '22 at 23:39
  • Thanks for correcting my wrong assumptions about the site rules. I just replaced \pgfmatrixcurrentrow (counter name) with #1 and it solved my problem (no idea why...) – Sergio Parreiras Jun 04 '22 at 23:46