パーセンテージの計算

パーセンテージの計算

calcこのパッケージを使用して、2 つの数値に基づいてパーセンテージを出力するマクロを作成しようとしました。たとえば\printpercent{100}{200}、100 は 200 の中間点であるため、50% と表示する必要があります。さまざまな組み合わせを試しましたが、意味のある結果を出力できないようです。以下は、私が試した多くの数式のうちの 1 つにすぎません。

\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\%}

より正確なソリューションが必要な場合、または入力が整数値ではない場合は、、、またはパッケージfpを使用できます。例:fltpointpgfmathl3fp

\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

もう 1 つの可能性は、 を使用することですpgfmathsiunitx精度が常に正しいかどうかはわかりませんが、この場合はfpuまたは を使用できます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} 

ここに画像の説明を入力してください

関連情報