4

I am trying to write a macro that prints numbers with a couple of options. The macro takes one optional argument that is the precision of the output and a starred version that attaches a unit to the number.

  • \printExpressionFormatted{expr} should evaluate the expression and print the result
  • \printExpressionFormatted[2]{expr} should evaluate the expression format the number to the given precision and print the result
  • \printExpressionFormatted*[2]{expr} and attach the units.

Here is the MWE

\documentclass{article}
\usepackage{xparse}
\usepackage{tikz}

\DeclareDocumentCommand\printExpressionFormatted{som}{
    \pgfmathparse{#3}
    \IfNoValueTF#2{\pgfmathresult}%
    {
        \pgfmathprintnumberto[/pgf/number format/fixed, precision=#2]{\pgfmathresult}{\myFormattedNumber}
        \IfBooleanTF#1{\myFormattedNumber~$\times~10^6 m^3$}{\myFormattedNumber}
    }
}


\begin{document}
\section{Testing}
\begin{tabular}{ll}
Unformatted & \printExpressionFormatted{746234.4485} \\
Formatted   & \printExpressionFormatted[2]{746234.4485} \\
Formatted with units &  \printExpressionFormatted*[2]{746234.4485} \\
\end{tabular}
\end{document}

The second and third incarnations work fine, however the first option (no formatting) generates the following error

! Missing number, treated as zero. <to be read again>

 l.19 ...d & \printExpressionFormatted{746234.4485}
3

You need to enclose the argument #2 of \IfNoValue in curly brackets, otherwise when not set #2 is essentially -NoValue- and only the first token gets eaten by the test.

Sample output

\documentclass{article}
\usepackage{xparse}
\usepackage{tikz}

\tracingmacros=1
\DeclareDocumentCommand\printExpressionFormatted{som}{
    \pgfmathparse{#3}
    \IfNoValueTF{#2}{\pgfmathresult}%
    {
        \pgfmathprintnumberto[/pgf/number format/fixed, precision=#2]{\pgfmathresult}{\myFormattedNumber}
        \IfBooleanTF#1{\myFormattedNumber~$\times~10^6 m^3$}{\myFormattedNumber}
    }
}

\begin{document}
\section{Testing}
\begin{tabular}{ll}
Unformatted & \printExpressionFormatted{746234.4485} \\
Formatted   & \printExpressionFormatted[2]{746234.4485} \\
Formatted with units &  \printExpressionFormatted*[2]{746234.4485} \\
\end{tabular}
\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.