[Tex/LaTex] How to use siunitx and tabularx together

siunitxtablestabularx

I'm using the tabular features of siunitx (for what it is worth: v1.3 since I'm on TexLive 2009) to align numbers in tables, eg.

\begin{tabular}{ p{1.5cm} S S S }
bla & 1.23 & 4.5 & 67.89 \tabularnewline
\end{tabular}

and that works perfectly fine.

Now I would like to have this table span a specific width, or rather to have several tables to have the same width. For this I would normally use tabularx

\begin{tabularx}{\textwidth}{ p{1.5cm} X X X }
bla & 1.23 & 4.5 & 67.89 \tabularnewline
\end{tabular}

Now, is there a way to combine the two? To have the number formatting and alignment features of siunitx inside an automatically resizing table?

Best Answer

The X column in tabularx is then converted to p{<width>} where width is automatically calculated. You can change this by redefining the \tabularxcolumn macro like described in the package manual:

\renewcommand{\tabularxcolumn}[1]{<column definition where #1 is the width>}

The S column uses the c column internally. To replace this with p{<width>} you have to manually place the internal column definition of S into \tabularxcolumn. The following code worked in my tests.

\documentclass{article}

\usepackage{array}
\usepackage{tabularx}
\usepackage{siunitx}


\begingroup
% Allow `_` and `:` in macro names (LaTeX3 style)
\catcode`\_=11
\catcode`\:=11
% Internal code of `S`
\gdef\tabularxcolumn#1{%
    >{\__siunitx_table_collect_begin:Nn S{} }%
    p{#1}%  <- this is different (is `c` in normal `S`)
    <{\__siunitx_table_print:}%
}
\endgroup

\begin{document}

\begin{tabularx}{\textwidth}{p{1.5cm} XXX}
     bla & 1.23 & 4.5  & 67.89 \\
     bla & 1.2  & 4.50 &  7.89 \\
     bla &  .2  &  .50 & 67.8 \\
\end{tabularx}
\end{document}
Related Question