# Arithmetic inside tikz

I'm having difficulty performing arithmetic inside tikz.

I've written:

  \foreach \s in {6,...,8}
{
\node[draw,red,circle] at (0:(\s-2)cm) {$\s$};
}


Somehow the arithmetic (\s-2) is not working, I think its the cm that's causing the issue but I need the measurement in cm.

Also if I write:

  \node[draw,red,circle] at (0:\s cm) {$(\s-2)$};


the arithmetic does not work and LaTeX just merrily shows (6-2) (7-2) etc...

• Welcome to TeX.SE! Please make your code snippet compilable ... – Mensch Oct 27 '18 at 6:36
• Here, you must use braces around your formula (tex.stackexchange.com/a/218542/14500) and multiply by 1cm: (0:{(\s-2)*1cm}) . – Paul Gaborit Oct 27 '18 at 6:55

The unit of tikz is the cm, so it is useless to specify it. As for the calculations, they are done here without the need for brackets.

\documentclass[tikz,border=5mm]{standalone}
\usetikzlibrary{calc}
\usetikzlibrary{positioning}

\begin{document}
\begin{tikzpicture}
\node[draw,blue,circle] at(0:2cm){4};
\node[draw,blue,circle] at(0:3){5};
\node[draw,blue,circle] at(0:4cm){6};
\foreach \s in {6,...,8}
{
\node[fill=red,circle,opacity=.5] at (0:\s-2) {$\s$};
}
\end{tikzpicture}
\end{document}


If you still want to specify the unit, it is necessary to do it after each of the Numbers: (0:\s cm-2cm) {$\s$};

Or to do as indicated by @PaulGaborit by factoring the unit: (0:{(\s-2)*1cm})

You can't use arithmetic as you shown directly (in the description of a node or if you explicitly put a unit of measure after it).

Just use evaluate option of the \foreach macro.

Here I create a new variable \mys which assumes the value \s-2.

In my first tikzpicture, \mys is used for positioning; in the second, for description:

\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\foreach[evaluate=\s as \mys using int(\s-2)] \s in {6,...,8}
{
\node[draw,red,circle] at (0:\mys cm) {$\s$};
}
\end{tikzpicture}

\begin{tikzpicture}
\foreach[evaluate=\s as \mys using int(\s-2)] \s in {6,...,8}
{
\node[draw,red,circle] at (0:\s cm) {$\mys$};
}
\end{tikzpicture}
\end{document}