# How to do math with numbers and units in a command

I want to create a 2-column wide table, that can change the width of the individual cells each row (in 5mm increments).

My Problem:

I'm trying to multiply a length (5mm) by an argument number. Also I need to subtract this argument from 18, but all I get is errors.

I wrote down what I mean, I hope it's clear what I'm trying to do.

\documentclass{article}

\newcommand{\tableLine}[3]{\multicolumn{#1}{|p{6*5mm}|}{#2} & \multicolumn{18-#1}{|p{(18-#1)*5mm}|}{#3}\\ \hline}

\begin{document}
\begin{tabular}{| *{18}{l|}}
\hline
\tableLine{6}{Left}{Right}
\end{tabular}
\end{document}


You can't mix the arithmetic of numbers and dimensions. So you need to make use of \numexpr and \dimexpr where needed.

\documentclass{article}

\newcommand{\tableLine}[3]{%
\multicolumn{#1}{ |p{#1\dimexpr5mm}| }{#2} &
\multicolumn{\numexpr18-#1}{ |p{\numexpr(18-#1)\dimexpr5mm}| }{#3} \\
\hline}

\begin{document}

\begin{tabular}{| *{18}{l|} }
\hline
\tableLine{6}{Left}{Right}
\end{tabular}

\end{document}


Alternatively, here is a definition using xfp that can handle numbers and dimensions interchangeably:

\usepackage{xfp}

\newcommand{\tableLine}[3]{%
\multicolumn{#1}{ |p{\inteval{#1*5mm}}| }{#2} &
\multicolumn{\inteval{18-#1}}{ |p{\inteval{(18-#1)*5mm}}| }{#3} \\
\hline}

• \dimexpr 5mm*(#1) and \dimexpr 5mm*(18-#1) work as well – egreg Oct 26 '17 at 16:46
• @egreg: Indeed. The key is to place a dimension first. – Werner Oct 26 '17 at 17:00