Search code examples
latexpdflatexoverleaf

Subtract integer from floats and integers in \foreach loop - (pdf)Latex [Overleaf]


I would like to subtract the integer 1 from the names of the files I have included in the for loop. Although this works for the integer values, the float doesn't decrease by one, but rather shows '63.1-1' for example. Would like help with this. Thank you!

I have tried using the math operator, using '\the\numexpr\x-1\relax'. The former didn't work for both floats and integers, while the later only worked for integers. You can find my code here:

\usepackage{graphicx, pgffor}
\foreach \x in {59, 60.1, 60.2, 62, 63.1, 63.2, 65, 66.1, 66.2, 67.1}{%
  \parbox{.4\textwidth}{\centering\includegraphics[width=\linewidth]{Figures/Graphs/Picture\x.png}\par \tiny Slide \the\numexpr\x-1\relax}\space%
}%

Solution

  • Tikz or PGF does not evaluate numbers. Use evaluate as directive inside foreach with an additional variable. As to the \numexpr, it only works with integers.

    \documentclass[12pt, a4paper]{article}
    \usepackage{graphicx,pgffor}
    \begin{document}
    \noindent
    \foreach \x [evaluate=\x as \y using {\x-1}]
        in {59, 60.1, 60.2, 62, 63.1, 63.2, 65, 66.1, 66.2, 67.1}{%
        \parbox{.4\textwidth}{%
            \centering
            \includegraphics[width=\linewidth]{example-image-duck}
            \par\small Slide \y}\space}
    \end{document}
    

    Edit. You can also work out the number using \pgfmathparse{}\pgfmathresult combo. The last line would be:

    \par\small Slide \pgfmathparse{\x-1}\pgfmathresult}\space}