[Tex/LaTex] using division to calculate column size

calculationscolumnslongtabletables

I am converting from another format and creating tables with varying numbers of columns. I would like the column to be approximately layed out. If there are two columns, I want each column to get half the space. Something like this:

\begin{longtable}{ p{\textwidth/2}  p{\textwidth/2} }

That is, for two columns, I want to divide the textwidth by two. Documentation elsewhere suggests that division should be possible using the forward slash character.

However, what I get is that both columns are the size of the full textwidth, and each cell starts with "/2". It is as if the /2 is being interpreted as "default text" to put in every cell, even the title row cells. See below:

enter image description here

Very strange. Every example I can find on the web has column width done by multiplying the textwidth by a decimal number. But that is inconvenient for me: When I have three columns I want it to be divided by three, and so on. I don't have the decimal for that fraction readily available.

Any idea what to do to get division working?

Best Answer

You can always in TeX (with no extra package) multiply a dimension register by a decimal number:

\documentclass{article}

\begin{document}

\begin{tabular}{ | p{.2\linewidth} | p{.25\linewidth} | }
  a & b
\end{tabular}

\end{document}

If you want to use syntax with slash for division, wrap it in \dimexpr:

\documentclass{article}

\begin{document}

\begin{tabular}{ | p{\dimexpr\linewidth/5\relax} | p{\dimexpr\linewidth/4\relax} | }
  a & b
\end{tabular}

\end{document}

Inside \dimexpr you can also do additions etc..., but the syntax 0.2*\linewidth is as illegal with it as it was with original Knuth TeX. You must not use the * at this location. The advantage of \dimexpr is to allow things such as

\dimexpr0.2\linewidth+3\tabcolsep-0.9876\dimexpr15pt\relax+\textwidth/25\relax

Notice that for some years now, the pdflatex format builds only on a pdftex which has the e-TeX extensions, inclusive of \dimexpr.

The calc package dates from an earlier era. You may still use it for some of its facilities such as \widthof, and chances are some package you use still loads it. It does not bring any computational facility that \dimexpr does not offer: none of them allow you to compute square roots for example (and computing a square root raises the question of the unit of your dimension).

The xfp solution is definitely overkill for adjusting by hand some column dimensions using multiplications and additions, but if you do need powers or square-root this is natural choice (there are other packages doing such computations).

Related Question