指向逗号宏

指向逗号宏

以下宏来自 wiki

\def\pointtocomma #1.#2{#1,#2}
\pointtocomma 123.456 % expands to 123,456

将点分隔的数字更改为逗号分隔的数字非常有用。但是,如果数字没有点,则宏扩展可能会导致一些错误。

是否可以重新定义它,以便

\pointtocomma 1.4 test % expands to 1,4 test
\pointtocomma 1 test % expands to 1 test

答案1

\def\ptc#1{\expandafter\doptc#1\q.\q}
\def\doptc#1.{\ptcremove#1\ifmmode\mathord\fi,}
\def\ptcremove#1\q#2\q{#1}

\ptc{108}
\ptc{1.08}
\ptc{.108}

答案2

困难的方式:

\documentclass{article}

\def\pointtocomma{\futurelet\next\checkpointordigit}
\def\checkpointordigit{%
  \ifx\next0\let\next\isdigit\else
  \ifx\next1\let\next\isdigit\else
  \ifx\next2\let\next\isdigit\else
  \ifx\next3\let\next\isdigit\else
  \ifx\next4\let\next\isdigit\else
  \ifx\next5\let\next\isdigit\else
  \ifx\next6\let\next\isdigit\else
  \ifx\next7\let\next\isdigit\else
  \ifx\next8\let\next\isdigit\else
  \ifx\next9\let\next\isdigit\else
  \ifx\next.\let\next\iscomma\else
  \let\next\relax
  \fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi
  \next
}
\def\isdigit#1{#1\pointtocomma}
\def\iscomma#1{{,}\pointtocomma}

\begin{document}

\pointtocomma 123.456 % expands to 123,456

\pointtocomma 1.4 test % expands to 1,4 test

\pointtocomma 1 test % expands to 1 test

\end{document}

在此处输入图片描述

具有更好的界面:

\documentclass{article}

\makeatletter
\newcommand{\pointtocomma}[1]{\point@to@comma#1.\@nil}
\def\point@to@comma#1.#2\@nil{%
  \if\relax\detokenize{#2}\relax
    % no point
    \expandafter\@firstoftwo
  \else
    \expandafter\@secondoftwo
  \fi
  {#1}%
  {\point@to@comma@aux#1.#2}%
}
\def\point@to@comma@aux#1.#2.{#1{,}#2}
\makeatother

\begin{document}

\pointtocomma{123.456} % expands to 123,456

\pointtocomma{1.4} test % expands to 1,4 test

\pointtocomma{1} test % expands to 1 test

\end{document}

当然,用下面这个更简单siunitx

\documentclass{article}
\usepackage{siunitx}

\sisetup{output-decimal-marker={,}}

\begin{document}

\num{123.456} \num{123,456}

\num{1.4} \num{1,4}

\num{1}

\end{document}

在此处输入图片描述

相关内容