1

I have a command that takes a single parameter. I want to add a constant number to that parameter and include it in the output. Something like (pseudo-code):

\newcommand*{\label}[1]{%
    Here is the sum: {#1 + 20}
}

% elsewhere... \label{22) % should output "Here is the sum: 42"

What's the simplest way of achieving this? Having googled a bit, I see talk of calc, fp, and other packages. Is there nothing that is simple and built-in to achieve this?

me--
  • 377
  • 2
  • 8

1 Answers1

2

There are a number of packages that can help you perform calculations or arithmetic. Here's its easy to use \inteval (from xfp) to evaluate an integer expression.

enter image description here

\documentclass{article}

\usepackage{xfp}

\newcommand*{\outputsum}[1]{% Here is the sum: \inteval{#1 + 20}% }

\begin{document}

\outputsum{22} % should output "Here is the sum: 42"

\end{document}

If you don't want to use a package and your calculations are fairly elementary, then you can also use

\newcommand*{\outputsum}[1]{%
  Here is the sum: \number\numexpr#1 + 20\relax%
}

For sums using decimals, the above won't work as a numeric expression assumes integer calculations.

And let's not use \label, as that's typically reserved for cross referencing.

Werner
  • 603,163