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?


    #1 & #2 & \pgfmathtruncatemacro{\foo}{#1}\foo \\%
    #1 & #2 & \pgfmathround{#1}\pgfmathresult \\%
    #1 & #2 & \pgfmathint{#1}\pgfmathresult \\%


Input & Expected & Output \\

Input & Expected & Output \\

Input & Expected & Output \\


1 Answer 1


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.

  • 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 .