計算百分比

計算百分比

我嘗試使用該calc包編寫一個宏,該宏根據兩個數字列印百分比。例如:\printpercent{100}{200}應該顯示 50%,因為 100 是 200 的中點。請參閱下文,了解我嘗試過的眾多公式之一:

\documentclass{article}
\usepackage{calc}
\newcounter{z}
\newcommand{\printpercent}[2]{%
    \setcounter{z}{#1 / #2 * 100}
    $#1/#2*100=\arabic{z}\%$
}%
\begin{document}
    \printpercent{1}{100}
    \printpercent{250}{200}
\end{document}

列印出:

1/100*100 = 0%

250/200*100 = 100%

  • 我如何計算這些數字的百分比?

答案1

計算僅適用於整數。您應該#1先乘以 100。

\documentclass{article}
\usepackage{calc}
\newcounter{z}
\newcommand{\printpercent}[2]{%
    \setcounter{z}{#1 * 100 / #2}
    $#1/#2*100=\arabic{z}\%$
}%
\begin{document}
    \printpercent{1}{100}
    \printpercent{250}{200}
\end{document}

而且使用 eTeX 比較簡單:

\newcommand\printpercent[2]{\the\numexpr#1*100/#2\%}

如果您需要更精確的解決方案,或者輸入不是整數值,您可以使用fpfltpoint或套件pgfmathl3fp實現。例如:

\documentclass{article}
\usepackage{fp}
\newcommand\printpercent[2]{\FPeval\result{round(#1*100/#2,1)}\result\%}
\begin{document}
    \printpercent{2.3}{100}
    \printpercent{176.5}{190.375}
\end{document}

答案2

pgfmath另一種可能性是與 一起使用siunitx。我不確定精度是否始終正確,在這種情況下可以使用fpuor fp

更新:對於使用它的用戶來說,tikz可以替換SI\pgfmathprintnumber

\documentclass{article} 

\input{pgfutil-common.tex}
\usepackage{pgfkeys,pgfmath}  
\usepackage{siunitx}

\newcommand{\printpercent}[3][2]{%  
    \pgfmathdivide{#2}{#3}% 
    \pgfmathmultiply{\pgfmathresult}{100}%
    \SI[round-mode=places,round-precision=#1]{\pgfmathresult}{\percent}
}%

\begin{document}    
     \printpercent[0]{1}{100}   
     \printpercent{200}{250}   
     \printpercent{2}{3}  
\end{document} 

在此輸入影像描述

相關內容