定义保存百分比的变量

定义保存百分比的变量

我想在 tex 文档中定义一些变量。例如,我写入.tex类似以下内容:Our tool succeeds to validate x samples out of all the y samples, thus its success ratio is z。其中z定义为x/y,并且x(分别为y)在其他地方以数字形式实例化,例如30(分别为47)。结果,编译后文本变为Our tool succeeds to validate 30 samples out of all the 47 samples, thus its success ratio is 63.8%

这样做的好处是,我只需要改变一些变量的值,就可以改变文本中的所有数字......困难在于z保存百分比数字。

有人知道如何实现这一点吗?

答案1

成功率

\documentclass{article}
\usepackage{xintfrac}

\newcommand\x{30}
\newcommand\y{47}


\newcommand\mypercent[3][1]{\xintRound {#1}{\xintE{#2/#3}{2}}\%}

\begin{document}\thispagestyle{empty}

Our tool succeeds to validate \x\ samples out of all the \y\ samples, thus its
success ratio is  
\mypercent{\x}{\y}.

Our competitor validated only 1 sample out of 31. Her success ratio is thus
\mypercent{1}{31}, or, more precisely \mypercent [3]{1}{31}.

\end{document}

答案2

\documentclass{article}

\newcommand\x{30}
\newcommand\y{47}


\newcommand\mypercent[2]{%
\expandafter\myadddot\the\numexpr 10000*(#1)/(#2)\relax\relax\%}

\def\myadddot#1#2#3{%
\ifx\relax#3%
.#1%
\else
#1\expandafter\myadddot\fi
#2#3}

\begin{document}


Our tool succeeds to validate \x\ samples out of all the \y\ samples, thus its success ratio is 
\mypercent{\x}{\y}


\end{document}

或 1dp

\newcommand\mypercent[2]{%
\expandafter\adddot\the\numexpr 1000*(#1)/(#2)\relax\relax\%}

\def\adddot#1#2{%
\ifx\relax#2%
.#1%
\else
#1\expandafter\adddot\fi
#2}

答案3

您还可以使用pgf数学引擎:

在此处输入图片描述

笔记:

  • 可选的第一个参数可用于控制显示的小数位数——如果未指定,则默认为 2 位数字。

代码:

\documentclass{article}
\usepackage{tikz}

\newcommand\x{30}
\newcommand\y{47}


\newcommand{\MyPercent}[3][2]{%
    \pgfmathparse{100*#2/#3}%
    \pgfmathprintnumber[fixed,precision=#1]{\pgfmathresult}\%%
}%


\begin{document}

Our tool succeeds to validate \x\ samples out of all the \y\ samples, thus its success ratio is 
\MyPercent{\x}{\y}, or with more digits \MyPercent[5]{\x}{\y}.

\end{document}

答案4

强制解决方案expl3;可选参数是小数位数(默认为 0);结果四舍五入。

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\DeclareExpandableDocumentCommand\mypercent{O{0}mm}
 {
  \fp_eval:n { round ( 100 * #2/#3 , #1 ) } \%
 }
\ExplSyntaxOff

\newcommand\x{30}
\newcommand\y{47}

\begin{document}

Our tool succeeds to validate \x\ samples out of all the \y\ samples, thus its
success ratio is
\mypercent{\x}{\y}.

Our competitor validated only 1 sample out of 31. Her success ratio is thus
\mypercent{1}{31}, or, more precisely \mypercent [3]{1}{31}.

\end{document}

在此处输入图片描述

相关内容