将小数转换为百分比值

将小数转换为百分比值

如何将给定的小数转换为逗号后具有一定位数 q 的相应百分比值?百分比应根据 q+1 四舍五入。

例如,我正在寻找类似

\percentage[逗号后的位置]{给定小数}

产生:

\percentage[positions-after-comma = 2]{0.12123456}: 12.12% 
\percentage[positions-after-comma = 4]{0.12123456}: 12.1235%
\percentage[positions-after-comma = 4]{2.12123456}: 212.1235%
\percentage[positions-after-comma = 1]{0.6789}: 67.9%
\percentage[positions-after-comma = 5]{0.6789}: 67.89000%

答案1

您可以使用该siunitx包:

\documentclass{article}

\usepackage{siunitx}

\newcommand\percentage[2][round-precision = 2]{% default precision: 2
    \SI[round-mode = places,
        scientific-notation = fixed, fixed-exponent = 0,
        output-decimal-marker={.}, #1]{#2e2}{\percent}%
}

\begin{document}

    \percentage{0.123456} % -> 12.35 %
    \percentage[round-precision = 3]{0.123456} % -> 12.345 %

\end{document}

答案2

您的值看起来是错误的。但除此之外:

\documentclass{article}
\usepackage{xfp,xparse}
\ExplSyntaxOn
\int_new:N\l_bjprim_round_int
\keys_define:nn {bjprim}
{
 positions-after-comma .int_set:N = \l_bjprim_round_int
}

\NewDocumentCommand\percentage { O{} m }
{
 \keys_set:nn {bjprim}{positions-after-comma=2,#1}
 \fpeval{round(#2*100,\l_bjprim_round_int)}\%
}
\ExplSyntaxOff
\begin{document}


\percentage[positions-after-comma = 2]{0.123456}: 12.12%

\percentage[positions-after-comma = 4]{0.123456}: 12.1235%

\percentage[positions-after-comma = 4]{2.123456}: 212.1235%

\percentage[positions-after-comma = 1]{0.6789}: 67.9%

\percentage[positions-after-comma = 5]{0.6789}: 67.89000%

\end{document}

如果你确实想用零填充,你可以用 siunitx 进行四舍五入:

\documentclass{article}
\usepackage{xfp,xparse,siunitx}
\ExplSyntaxOn
\int_new:N\l_bjprim_round_int
\keys_define:nn {bjprim}
{
 positions-after-comma .int_set:N = \l_bjprim_round_int
}

\NewDocumentCommand\percentage { O{} m }
{
 \keys_set:nn {bjprim}{positions-after-comma=2,#1}
 \num[round-mode = places,round-precision=\l_bjprim_round_int]{\fpeval{#2*100}}\%
}
\ExplSyntaxOff
\begin{document}


\percentage[positions-after-comma = 2]{0.123456}: 12.12%

\percentage[positions-after-comma = 4]{0.123456}: 12.1235%

\percentage[positions-after-comma = 4]{2.123456}: 212.1235%

\percentage[positions-after-comma = 1]{0.6789}: 67.9%

\percentage[positions-after-comma = 5]{0.6789}: 67.89000%

\end{document}

在此处输入图片描述

相关内容