10

The pgfmath functions give me unexpected results when used on numbers with leading zeros. Are the output in the example below expected for 0011 and 0021?

\documentclass{article}
\usepackage{tikz}

\newcommand\truncateline[2]{% 
    #1 & #2 & \pgfmathtruncatemacro{\foo}{#1}\foo \\%
}
\newcommand\roundline[2]{% 
    #1 & #2 & \pgfmathround{#1}\pgfmathresult \\%
}
\newcommand\intline[2]{% 
    #1 & #2 & \pgfmathint{#1}\pgfmathresult \\%
}

\begin{document}

\section{pgfmathtruncatemacro}
\begin{tabular}{lll}
Input & Expected & Output \\
\truncateline{0}{0}
\truncateline{1}{1}
\truncateline{01}{1}
\truncateline{001}{1}
\truncateline{0011}{11}
\truncateline{0021}{21}
\end{tabular}

\section{pgfmathround}
\begin{tabular}{lll}
Input & Expected & Output \\
\roundline{0}{0}
\roundline{1}{1}
\roundline{01}{1}
\roundline{001}{1}
\roundline{0011}{11}
\roundline{0021}{21}
\end{tabular}

\section{pgfmathint}
\begin{tabular}{lll}
Input & Expected & Output \\
\intline{0}{0}
\intline{1}{1}
\intline{01}{1}
\intline{001}{1}
\intline{0011}{11}
\intline{0021}{21}
\end{tabular}

\end{document}
0

1 Answer 1

11

The pgfmanual states (section 62.1 Commands for Parsing Expressions, page 526 with v2.10):

An integer with a zero-prefix (excluding, of course zero itself), is interpreted as an octal number and is automatically converted to base 10.

So 021 or 0021 is actually 2x8+2x1 = 17, not 21.

You would need to avoid or remove the leading 0s, e.g. using a recursive macro like:

\def\removeleadingzeros#1{\if0#1 \expandafter\removeleadingzeros\else#1\fi}

This however doesn't work in the general case (breaks e.g. with only 0 or 00 etc.). Expanding the number with \the\numexpr <number>\relax would also turn e.g. 0021 into 21, but this would of course limit the usefulness of using pgfmath in the first place.


After searching the manual and looking at the source code of pgfmathparser.code.tex this behavior seems to be hard coded and is not configurable.

3
  • In my case I am expecting integer input (possibly with leading 0). Appending a .0 to the input causes pgf to interpret the numbers in base 10 irrespective of the leading 0. \pgfmathtruncatemacro{\foo}{0021.0}\foo gives 21 as desired. Apr 17, 2012 at 10:33
  • Martin can you elaborate on why using \the\numexpr <number>\relax would limit the usefulness of using \pgfmath. This seems to be working for me but just wanted to make sure that there is not some other problem with this. Also, using \pgfmathparse{\removeleadingzeros{31} - \removeleadingzeros{07}}\pgfmathresult yields Argument of \removeleadingzeros has an extra }., but works fine if I replaced the 07 with just 7. Sep 22, 2012 at 18:36
  • @PeterGrill: In that case <number> can only by a valid numexpr, so all advanced pgfmath expressions are no longer allowed. Sep 23, 2012 at 7:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .