How to "add" units to results of \pgfmathsetmacro?

\pgfmathsetmacro calculates a length and gives back the result in pt but without the unit pt attached - the macro contains simply a number. So if you want to use this number in a sensible way you should reattach the pt:

\documentclass{standalone}
\usepackage{tikz}
\begin{document}

\def\ri{1.0cm} % define inner diameter
\def\ro{2.0cm} % define outer diameter

\begin{tikzpicture}
  \pgfmathsetmacro{\dr}{\ro-\ri} % compute width
  \pgfmathsetmacro{\rm}{(\ri+\ro)/2} % compute mean diameter
  \show\rm %<--- shows > \rm=macro: ->42.67912.
  \draw[red,line width=\dr] (0:\rm pt) arc (0:360:\rm pt);
  \draw[black] (0,0) circle (\ro) circle (\ri);
\end{tikzpicture}

\end{document}

Instead of \pdfmathsetmacro you can use \pgfmathsetlengthmacro

\documentclass{standalone}
\usepackage{tikz}
\begin{document}

\def\ri{1.0cm} % define inner diameter
\def\ro{2.0cm} % define outer diameter

\begin{tikzpicture}
  \pgfmathsetlengthmacro{\dr}{\ro-\ri} % compute width
  \pgfmathsetlengthmacro{\rm}{(\ri+\ro)/2} % compute mean diameter
  \show\rm % > \rm=macro: ->42.67912pt.
  \draw[red,line width=\dr] (0:\rm) arc (0:360:\rm);
  \draw[black] (0,0) circle (\ro) circle (\ri);
\end{tikzpicture}

\end{document}

enter image description here


Very simple: divide or multiply by 1cm. That way you can work in any units you like, such as cm. (I do not recommend using \rm for a macro name, though.)

\documentclass{standalone}
\usepackage{tikz}
\begin{document}

\def\ri{1.0cm} % define inner diameter
\def\ro{2.0cm} % define outer diameter

\begin{tikzpicture}
  \pgfmathsetmacro{\dr}{\ro-\ri} % compute width
  \pgfmathsetmacro{\rm}{(\ri+\ro)/2cm} % compute mean diameter
  \typeout{\rm}
  \draw[red,line width=\dr] (0:\rm*1cm) arc (0:360:\rm*1cm);
  \draw[black] (0,0) circle (\ro) circle (\ri);
\end{tikzpicture}

\end{document}

enter image description here