1

I was trying to find a way to write numbers in a specific manner in tikz (I wanted to get rid of the ".0". See code below). I struggled for a certain time, until I found percusse's answer (I didn't know the int() function existed). Now I have a working solution for what I need.

However, during my search for the perfect formatting of the numbers, I stumbled upon this document. In section 92 - Number Printing (on page 945), the \pgfmathprintnumber and the \pgfkeys commands/macros and the format/precision option for \pgfkeys are described. It seemed to be a good idea, but for some reason, it didn't work. I still cannot figure out why it doesn't work. Here is a sample code:

\documentclass[10pt]{article}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
    \pgfkeys{/pgf/number format/.cd,fixed,precision=0} % "precision = 0" does not print the trailling zeroes

    \draw[domain=0:10,smooth,variable=\x,blue,samples=100] plot ({\x},{sin(\x * pi r)}); % Sine
    \draw (0, 0) node[left] {AC voltage};
    \draw[dashed] (0, 0) -- (10, 0);
    \foreach \x in {0, 2, ..., 10} { \draw[dashed] (\x, -1.25) -- (\x, 2); } % Vertical lines
    \foreach \x in {0, 2, ..., 8}
    {
        % Problematic line:
        \draw[<->] (\x, -1.2) -- node[below] {\pgfmathprintnumber{\x/2+1}} (\x + 2, -1.2); % This line doesn't work
%       \draw[<->] (\x, -1.2) -- node[below] {\pgfmathparse{int(\x/2+1)}\pgfmathresult} (\x + 2, -1.2); % This line works perfectly
    }

\end{tikzpicture}
\end{document}

The error I get is

! Package PGF Math Error: Could not parse input '0/2+1' as a floating point number, sorry. The unreadable part was near '/2+1'..

I tried to play around with \pgfmathprintnumberto and format/fixed zerofill=boolean, as described in the manual, but nothing seemed to work.

Thanks in advance!

4

You need to use \pgfmathparse for the computation and then \pgfmathprintnumber to print the result.

Here's your modified MWE:

\documentclass[10pt]{article}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
    \pgfkeys{/pgf/number format/.cd,fixed,precision=0} % "precision = 0" does not print the trailling zeroes

    \draw[domain=0:10,smooth,variable=\x,blue,samples=100] plot ({\x},{sin(\x * pi r)}); % Sine
    \draw (0, 0) node[left] {AC voltage};
    \draw[dashed] (0, 0) -- (10, 0);
    \foreach \x in {0, 2, ..., 10} { \draw[dashed] (\x, -1.25) -- (\x, 2); } % Vertical lines
    \foreach \x in {0, 2, ..., 8}
    {
        % Problematic line:
        \draw[<->] (\x, -1.2) -- node[below] {\pgfmathparse{\x/2+1}\pgfmathprintnumber\pgfmathresult} (\x + 2, -1.2); % This line doesn't work
    }

\end{tikzpicture}
\end{document}
| improve this answer | |

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.