[Tex/LaTex] siunitx, bold numbers in cell with cell content start with \$

boldsiunitx

Based on egreg answer on question how-can-i-make-siunitxs-num-bold i try to make the following table:

\documentclass[12pt,
               border=2mm,
               preview]{standalone}
    \usepackage{booktabs}
\usepackage{siunitx}
    \usepackage{etoolbox}
\renewcommand{\bfseries}{\fontseries{b}\selectfont}
\newrobustcmd{\B}{\bfseries}

\begin{document}
%---------------------------------------------------------------%
    \begin{table}
\sisetup{detect-weight, mode=text, table-format=2.2}
    \centering
\begin{tabular}{ l >{\$}S[table-align-text-pre=false,
                          table-space-text-pre =\$ ]
                        S[table-space-text-post=\,]<{\%}
               }
\toprule
text a  &   \B  17.89   &   \B  10.29   \\
text b  &        0.29   &        7.89   \\
\bottomrule
\end{tabular}
    \end{table}
\end{document}

which gives:

enter image description here

Is possible to convince siunitx that also the second cell in the first row to be write in bold?

Best Answer

This happens as siunitx is trying to maintain alignment. The material before the number is typeset in a box, which means that any colour or font change commands will be lost. You don't see that with just a font switch as it's zero-width: that's detected and inserted directly (not boxed). You can get around this by making the inserted material have zero width:

\documentclass[12pt,
               border=2mm,
               preview]{standalone}
    \usepackage{booktabs}
\usepackage{siunitx}
    \usepackage{etoolbox}
\renewcommand{\bfseries}{\fontseries{b}\selectfont}
\newrobustcmd{\B}{\bfseries}

\begin{document}
%---------------------------------------------------------------%
    \begin{table}
\sisetup{detect-weight, mode=text, table-format = 2.2}
    \centering
\begin{tabular}{ l >{{\makebox[0pt][l]{\$}}}S[table-align-text-pre=true,
                          table-space-text-pre =\$ ]
                        S[table-space-text-post={\,\%}]<{\,\%}
               }
\toprule
text a  &   \B 17.89   &   \B  10.29\cr
text b  &        0.29   &        7.89\cr
\bottomrule
\end{tabular}
    \end{table}
\end{document}

A bug shows up in siunitx when you do this as the $ tokens are duplicated. A fix will be on CTAN later today. It can be fixed for the moment using

\ExplSyntaxOn
\patchcmd \__siunitx_table_print_S_reserved_ends:
  { \l__siunitx_table_collect_pre_tl \bool_set_false:N }
  { \box_clear:N \l__siunitx_table_pre_box
    \l__siunitx_table_collect_pre_tl \bool_set_false:N
  }
  { }
  { }
\ExplSyntaxOff