8

I'm trying to implement an invoice calculation in LaTeX and using PGF as the method to do calculations. I've run into an odd problem where it seems that PGF calculates things incorrectly and I'm not sure what's causing it. Here's a minimal example:

\documentclass{standalone}

\usepackage{pgf}
\usepgflibrary{fpu}
\pgfkeys{
    /pgf/fpu=true,
    /pgf/number format/.cd,
    precision=2,
    fixed,
    fixed zerofill,
    use comma,
    1000 sep={.}
}

\begin{document}

\pgfmathparse{(1*800050)}\pgfmathprintnumber{\pgfmathresult}

\end{document}

Why does this output 800.050,05 when it should output 800.050,00?

user27875
  • 163

2 Answers2

8

I don't think you can count on eight exact digits with the fpu library; quoting the manual, section 54.3,

The FPU has a uniform relative precision of about 4–5 correct digits.

You might use the fp library of expl3 and rely on PGF for the number printing:

\documentclass[margin=2bp,varwidth]{standalone}
\usepackage{expl3}
\ExplSyntaxOn
\cs_set_eq:NN \fpeval \fp_eval:n
\ExplSyntaxOff

\usepackage{pgf}
\pgfkeys{
    /pgf/number format/.cd,
    precision=2,
    fixed,
    fixed zerofill,
    use comma,
    1000 sep={.}
}

\begin{document}

\pgfmathprintnumber{\fpeval{1*800050}}

\pgfmathprintnumber{\fpeval{800050/4}}

\pgfmathprintnumber{\fpeval{800050/8}}

\end{document}

enter image description here

egreg
  • 1,121,712
5

If you don't mind compiling with lualatex than you can exploit the mathematical capabilities of lua:

\documentclass[border=5]{standalone}
\usepackage{pgf,pgffor}
\def\luamath#1{\edef\luamathresult{\directlua{tex.write("" .. #1)}}}
\pgfkeys{
    /pgf/number format/.cd,
    precision=2,
    fixed,
    fixed zerofill,
    use comma,
    1000 sep={.}
}
\begin{document}
\parbox{.75in}{
  \foreach \i in {1,...,10}{
    \luamath{800050/\i}\pgfmathprintnumber{\luamathresult}\\
  }
}
\end{document}

enter image description here

Mark Wibrow
  • 70,437
  • Why the \edef here rather than \def\luamath#1{\directlua{tex.write("" .. #1)}} and \pgfmathprintnumber{\luamath{800050/\i}}? – Joseph Wright Aug 13 '14 at 16:23
  • @JosephWright no reason specifically, I don't think I thought about it that much. I guess it was just "sort of" analogous to \pgfmathparse putting the result of a calculation in \pgfmathresult. – Mark Wibrow Aug 13 '14 at 18:16