[Tex/LaTex] Get value of a counter

countersmacros

Consider this code:

\documentclass{report}
\newcounter{counterA}
\newcounter{counterB}
\begin{document}
...
\setcounter{counterA}{2}
\setcounter{counterB}{3}
\addtocounter{counterB}{counterA}
\end{document}

When I compile I get the following error:

! Missing number, treated as zero.
<to be read again> 
                   c
l.8 \addtocounter{counterB}{counterA}

How to add the value in counterA to counterB?

Best Answer

You can access the value of a counter for arithmetic or other situations where LaTeX expects a number with \value{<countername>}, so

\addtocounter{counterB}{\value{counterA}}

should be what you are looking for.

You would use \the<countername> to print (a representation of) the value.

\thecounterB

Gives

5

in the example.

In rare situations or when you define \the<countername> you may have to use

\arabic{<countername>}
\roman{<countername>}
\Roman{<countername>}
\alph{<countername>}
\Alph{<countername>}

to force a particular printed representation.