[Tex/LaTex] Arithmetic/calculations with lengths

calculationslengthsspacing

I want to define a new command to add vertical "padding" before and after the content of a table cell. I'm stealing the idea of using rules/struts from the accepted answer to this question.

My concept is something like

\newcommand{\vpad}[2]{
   \rule{0pt}{\baselineskip + #1}              % top padding
   \rule[-0.4*\baselineskip - #2]{0pt}{0pt}}   % bottom padding

I know that there are many cases where this won't work, but that's not the issue, at present. My question is about the arithmetic expressions involving \baselineskip and the command arguments. Clearly I don't have the syntax correct. So, what is the right syntax for this sort of thing?

Edit
I'm starting to think that things like 0.4*baselineskip - #2 are not allowed. If so, maybe I have to settle for '-4pt – #2'. Is negation allowed?

Best Answer

There are several ways to calculate equations in (La)TeX. (Therefore I created the adjcalc package as part of the adjustbox bundle so that users can select which way they want it.).

You can either 1) use eTeX macros like \dimexpr, \glueexpr, 2) the calc package or 3) the pgfmath package.

The simplest thing is to use \dimexpr ... \relax. It expands to the calculation result. The \relax can be used as an endmarker which is also removed in the expansion. This requires eTeX (extended TeX) which is part of all main TeX distributions.

\newcommand{\vpad}[2]{
   \rule{0pt}{\dimexpr\baselineskip + #1\relax}              % top padding
   \rule[\dimexpr-0.4*\baselineskip - #2\relax]{0pt}{0pt}}   % bottom padding
Related Question