[Tex/LaTex] Calculating percentage

calculationsmacros

I have tried to use the calc package to write a macro which prints a percentage based on two numbers. E.g.: \printpercent{100}{200} should display 50% as 100 is the half-way point of 200. I have tried many different combinations, but cannot seem to get any meaningful answers printed. See below, for just one of the many formulas I have tried:

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

That prints out:

1/100*100 = 0%

250/200*100 = 100%

  • How can I calculate a percent from these numbers?

Best Answer

The calculation are for intergers only. You should multiply #1 by 100 first.

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

And it is easier to use eTeX:

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

If you need more precise solution, or the input is not interger values, you can use fp, fltpoint, pgfmath or l3fp packages for this. For example:

\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}
Related Question