[Tex/LaTex] How to calculate the difference of 2 counters (pageref)

calculationscounterspage-numbering

  • How can I calculate the difference between 2 counters (like page numbers), so that pdfLateX outputs "3" in the last line of my example?

  • and how could I calculate the difference between the "current" page (where the calculation is printed) and \pageref{A} (without explicitly defining \label{B})?

Example:

\documentclass{scrbook}

\usepackage[ngerman]{babel} 
\usepackage[latin1]{inputenc}

\begin{document}

Here is label A \label{A}

\newpage
text
\newpage
text
\newpage

Here is label B \label{B}

There are \pageref{B}-\pageref{A} pages between labels A and B. 

\end{document}

Best Answer

The refcount package can extract the number from a reference. That only works for arabic page numbers, of course. And there must not be any \addtocounter{page}{...} or \setcounter{page}{...} between A and B. For those more complicated situations, \theCurrentPage of the pageslts package can be used.

\documentclass{scrbook}

\usepackage[ngerman]{babel}
\usepackage[latin1]{inputenc}

\usepackage{refcount}

\usepackage{pageslts}

\pagenumbering{arabic}

\begin{document}

Here is label A. \label{A}

\newpage
text
\newpage
text
\newpage

Here is label B \label{B}

\makeatletter
\@tempcnta=\getpagerefnumber{B}\relax%
\advance\@tempcnta by -\getpagerefnumber{A}%
% (maybe
% \advance\@tempcnta by -1%
% depending on your definition of "between")
\xdef\pagedifference{\the\@tempcnta}%
\makeatother

There are \pagedifference~pages between labels A and B.

\makeatletter
\@tempcnta=-\getpagerefnumber{A}\relax%
\advance\@tempcnta by \thepage%
% (maybe \advance\@tempcnta by -1, depending on definition of "between")
\xdef\pagedifference{\the\@tempcnta}%
\makeatother

There are \pagedifference~pages between labels A and the current page.


\newpage
\pagenumbering{Roman}

Here is page \thepage{} (the \theCurrentPage{}.~page).
\xdef\mypageA{\theCurrentPage}

\newpage
text
\newpage
text
\addtocounter{page}{10}
Just added 10 to the page number here.

\newpage

Here is page \thepage{} (the \theCurrentPage{}.~page).
\xdef\mypageB{\theCurrentPage}

\makeatletter
\@tempcnta=\mypageB\relax%
\advance\@tempcnta by -\mypageA%
% (maybe \advance\@tempcnta by -1, depending on definition of "between")
\xdef\pagedifference{\the\@tempcnta}%
\makeatother

There are \pagedifference~pages between page A and the current page B.

\end{document}