![您能否让表格自动格式化数字以在负数上显示括号?](https://linux22.com/image/342640/%E6%82%A8%E8%83%BD%E5%90%A6%E8%AE%A9%E8%A1%A8%E6%A0%BC%E8%87%AA%E5%8A%A8%E6%A0%BC%E5%BC%8F%E5%8C%96%E6%95%B0%E5%AD%97%E4%BB%A5%E5%9C%A8%E8%B4%9F%E6%95%B0%E4%B8%8A%E6%98%BE%E7%A4%BA%E6%8B%AC%E5%8F%B7%EF%BC%9F.png)
在这个答案对于我所关联的问题,我在括号中显示了负数,因此需要在答案中添加它们作为前后文本。我现在从这个解决方案中得出的问题是,如果我在表格中输入负数,是否可以将其格式化为 Latex 格式以显示在括号中。因此,在下面的 MWE 中,{(}50000{)}
我可以输入 -50000,而不是键入,输出将是 (50000)。
\documentclass[12pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{booktabs}
\usepackage{siunitx}
\sisetup{group-separator={,}}
\begin{document}
\section*{Income \& Expenditure Account}
\begin{table}[htb]
\centering
\begin{tabular}{
p{7.5cm}
c
*2{S[table-format=6.0, table-space-text-pre=(, table-space-text-post=)]}
}
& \textbf{Note} & {\textbf{2016}} & {\textbf{2015}} \\
\midrule
Income & 1 & 100000 & 102000 \\
\cmidrule{3-4}\\
Cost of Sales & 2 & {(}50000{)} & {(}45000{)} \\
\cmidrule{3-4}
Gross Profit & & 50000 & 57000 \\
\end{tabular}
\end{table}
\end{document}
答案1
虽然重新发明轮子很有趣,但我还是决定使用xstring
和siunitx
包。
宏\acount
和\bcount
用于将数字格式化为使用(正数)表示负数。\bcount
将整数转换为小数。
第二步是创建新的列类型 A 和 B,它们会自动扩展这些宏。请注意\multicolumn
顶行中的用来处理文本。
\documentclass[12pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{booktabs}
\usepackage{collcell}
\usepackage{xstring}
\usepackage{siunitx}
\newcommand{\acount}[1]% #1 = number
{\IfBeginWith{#1}{-}{\StrBehind{#1}{-}[\temp](\num[group-separator={,}]{\temp}\rlap{)}}%
{\num[group-separator={,}]{#1}}}
\newcommand{\bcount}[1]% #1 = decimal number
{\IfBeginWith{#1}{-}{\StrBehind{#1}{-}[\temp]%
(\num[group-separator={,},round-mode=places,round-precision=2,round-integer-to-decimal]{\temp}\rlap{)}}%
{\num[group-separator={,},round-mode=places,round-precision=2,round-integer-to-decimal]{#1}}}
\newcolumntype{A}{>{\collectcell\acount}r<{\endcollectcell}}
\newcolumntype{B}{>{\collectcell\bcount}r<{\endcollectcell}}
\begin{document}
\section*{Income \& Expenditure Account}
\begin{table}[htb]
\centering
\begin{tabular}{p{8.25cm}cAA}
& \textbf{Note} & \multicolumn{1}{r}{\textbf{2016}} & \multicolumn{1}{r}{\textbf{2015}} \\ \hline\\
Income & 1 & 100000 & 102000 \\ \cline{3-4}\\
Cost of Sales & 2 & -50000 & -45000 \\ \cline{3-4}
Gross Profit & & 50000 & 57000 \\
\end{tabular}
\end{table}
\section*{Income \& Expenditure Account}
\begin{table}[htb]
\centering
\begin{tabular}{p{8.25cm}cBB}
& \textbf{Note} & \multicolumn{1}{r}{\textbf{2016}} & \multicolumn{1}{r}{\textbf{2015}} \\ \hline\\
Income & 1 & 100000 & 102000 \\ \cline{3-4}\\
Cost of Sales & 2 & -50000 & -45000 \\ \cline{3-4}
Gross Profit & & 50000 & 57000 \\
\end{tabular}
\end{table}
\end{document}