11

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

instead of:

2 * 10 = 20

?

15

\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}

enter image description here

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}

enter image description here

2
  • Thanks. Any way to produce integer result instead of real number? Nov 6 '16 at 18:30
  • @pasabaporaqui See the updated answer.
    – gernot
    Nov 6 '16 at 18:41
10

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}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.