# pgfmathparse basic usage

Please, what I'm doing wrong in this test:

\documentclass{article}

\usepackage{tikz}

\begin{document}
\begin{tikzpicture}

\pgfmathparse{10*2}
\node at (4,-5) {$2 \cdot 10 = \pgfmathresult$};

\end{tikzpicture}
\end{document}


It gives as output a line:

2 * 10 = -5.0


2 * 10 = 20


?

\pgfmathresult holds the result of the last computation done by pgfmath; in this case this was the evaluation of the y-coordinate of (4,-5), which happens to be -5. Use \pgfmathsetmacro to assign the result to a macro.

\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\pgfmathsetmacro\result{10*2}
\node at (4,-5) {$2 \cdot 10 = \result$};
\end{tikzpicture}
\end{document}


To obtain an integer value, use \pgfmathtruncatemacro instead of \pgfmathsetmacro. For more information see the TikZ manual; in version 3.0.1a this topic is presented in section 89 on page 923.

\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\pgfmathtruncatemacro\result{10*2}
\node at (4,-5) {$2 \cdot 10 = \result$};
\end{tikzpicture}
\end{document}


• Thanks. Any way to produce integer result instead of real number? Nov 6, 2016 at 18:30
• @pasabaporaqui See the updated answer. Nov 6, 2016 at 18:41

tikz performs some calculations when using \nodes. These calculations are done using \pgfmathparse. As such, your \pgfmathresult is overwritten with something else.

Instead, place the \pgfmathparse immediately before \pgfmathresult, or store \pgfmathresult immediately after evaluating it for use later:

\documentclass{article}

\usepackage{tikz}

\begin{document}

\begin{tikzpicture}
\pgfmathparse{10*2}\edef\storeresult{\pgfmathresult}%
\node at (4,-5) {$2 \cdot 10 = \pgfmathprintnumber\storeresult$};
\node at (4,-6) {$2 \cdot 10 = \pgfmathparse{10*2}\pgfmathprintnumber\pgfmathresult$};
\end{tikzpicture}

\end{document}