How to display the final value of a counter at the beginning of a document?

The totcount package does just it:

\usepackage{totcount}
\newtotcounter{mycount}

With \newtotcounter{mycount} you define a new counter and also register it; if the counter is already defined (say chapter), then

\regtotcounter{chapter}

will simply register it to totcount system.

You can print the final value of the counter (as it was on the preceding LaTeX run) by \total{mycount}. There is also \totvalue{mycount} which is the analog of \value{mycount}. A couple of LaTeX runs are necessary to get synchronization.


Here is some code for Martin's comment:

\documentclass{article}
\usepackage{scrlfile}% KOMA-Script package with it's own documentation

\makeatletter
\newcommand*{\demomycounter}{% This is only for demonstration and not part of the suggestion
  \@whilenum \value{page}<2\do {%
    Usage of mycounter with value \stepcounter{mycounter}\themycounter.\par
  }%
}
\newcommand*\storecounteratend[1]{% command to tell LaTeX to save the last value for the next run
  \BeforeClosingMainAux{%
    \immediate\write\@auxout{%
      \string\restorecounteratbegin{#1}{\csname the#1\endcsname}%
    }%
  }%
}
\newcommand*{\restorecounteratbegin}[2]{% used at the aux file
  \expandafter\gdef\csname stored@#1\endcsname{#2}%
}
\newcommand*{\storedcounter}[1]{% user command to ask for the value
  \@ifundefined{stored@#1}{???}{\csname stored@#1\endcsname}%
}
\makeatother

\newcounter{mycounter}
\storecounteratend{mycounter}

\begin{document}
Last value of mycounter was \storedcounter{mycounter}.
\demomycounter
\end{document}

Instead of using \BeforeClosingMainAux from package scrlfile, you may use \AfterLastShipout with package atveryend.

Another solution would be to use \refstepcounter instead of \stepcounter. In this case, you simply have to write a label at the end of the document and may use \ref:

\documentclass{article}
\usepackage{scrlfile}

\newcounter{mycounter}
\BeforeClosingMainAux{\label{mycounter}}

\makeatletter
\newcommand*{\demomycounter}{% This is only for demonstration and not part of the suggestion
  \@whilenum \value{page}<2\do {%
    Usage of mycounter with value \refstepcounter{mycounter}\themycounter.\par
  }%
}

\begin{document}
Last value of mycounter was \ref{mycounter}.
\demomycounter
\end{document}

If you need not a reference to the counter but the value, you may combine the second suggestion with package refcount.


In ConTeXt, you don't need any external package to display the final value of a counter: it is available by using the macro \lastcounter[...]. For example:

\definecounter[countername][numberconversion=Characters]

\starttext

There are \lastcounter[countername] counters.

\dorecurse{5}
  {\convertedcounter[countername] randomtext \incrementcounter[countername] \crlf }

\stoptext

To access the last value of the counter at the Lua end, use

structures.counters.last("countername", 1)

Tags:

Counters