如何从宏输出值创建逗号格式的数字?

如何从宏输出值创建逗号格式的数字?

在下面的文档中,我希望数字有一个千分之一分隔符逗号。

\documentclass{article}
\usepackage{totcount}
\begin{document}

\newtotcounter{fund}
\newcommand{\fund}[1]{\addtocounter{fund}{#1}#1}

In total, my funding was \$\total{fund}.

My first funding was worth \$\fund{3000}.

My second funding was worth \$\fund{50000}.

\end{document}

我已尝试过序言中的sistylesiunitx包,但无济于事。

\usepackage{sistyle}
    \SIthousandsep{,}

或者

\usepackage[group-separator={,}]{siunitx}

我怎样才能在这些值之间添加逗号而不破坏代码?

答案1

更新问题的解决方案

在我发布答案后,问题已更新。这是更新后的解决方案。它使用了refcount 包。

您需要随时将总数保存在标签中,然后在需要时使用它。

\documentclass{article}
\usepackage{refcount}

\usepackage[group-separator={,}]{siunitx}

\makeatletter
\def\refcounter#1{%
  \protected@edef\@currentlabel
  {\csname p@#1\endcsname\csname the#1\endcsname}%
}
\makeatother

\newcounter{fund}
\def\fund#1{\addtocounter{fund}{#1}\$\num{#1}}
\def\SaveTotal#1#2{\refcounter{#1}\label{#2}}
\newcounter{showtotal}
\def\ShowTotal#1{\setcounterref{showtotal}{#1}\${\num{\arabic{showtotal}}}}

\begin{document}

After the second one, my total funding was \ShowTotal{totalOne}.

And my third and fourth funding made my total funding  \ShowTotal{totalTwo}.

My first funding was worth \fund{3000}.

My second funding was worth \fund{50000}.

\SaveTotal{fund}{totalOne}

Then, I got a third funding of \fund{150000}.

And finally got a fourth funding of \fund{50000000}.

\SaveTotal{fund}{totalTwo}

\end{document}

更新后的输出

在此处输入图片描述


原始问题的解决方案

基础

仅使用该siunitx包并不能确保(也不应该)所有数字都自动格式化。您需要明确调用该\num命令才能格式化数字。

因此,我\fund稍微修改了你的命令,并定义了\Total显示计数器值的命令。

(我擅自在宏中放入了 $ 符号。)

代码

\documentclass{article}
\usepackage{totcount}

\usepackage[group-separator={,}]{siunitx}

\begin{document}

\newtotcounter{fund}
\newcommand{\fund}[1]{\addtocounter{fund}{#1}\$\num{#1}}
\def\Total#1{\$\num{\arabic{#1}}}

My first funding was worth \fund{3000}.

My second funding was worth \fund{50000}.

Thus, in total, my funding was \Total{fund}.

\end{document}

输出

在此处输入图片描述

答案2

您可以实现自己的totcount\label使用-进行类似设置\ref

在此处输入图片描述

\documentclass{article}

\usepackage{siunitx}
\sisetup{group-separator={,}}

\makeatletter
\newcommand{\newtotcounter}[1]{%
  \newcounter{tot:#1}% Create new counter
  \g@addto@macro\@enddocumenthook{% ~ \AtEndDocument...
    \def\@currentlabel{\protect\num{\arabic{tot:#1}}}% ... update \@currentlabel and ...
    \label{tot:#1}}}% ... mark with \label.
\makeatother

\newtotcounter{fund}

\newcommand{\fund}[1]{\addtocounter{tot:fund}{#1}\$\num{#1}}% Increment tot:fund counter
\newcommand{\total}[1]{\$\ref{tot:#1}}% Recall tot:#1 \label

\begin{document}

In total, my funding was \total{fund}.

My first funding was worth \fund{3000}.

My second funding was worth \fund{50000}.

\end{document}

相关内容