# Calculating percentage

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}{%
\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?
• Is the input always integer values? What sort of range of input needs to work? Are you looking for accuracy to whole percentage points or more than that? – Joseph Wright Dec 6 '11 at 15:55
• All of the numbers are integers. For the time being, I only need between 1 and 1 million, but for the future, might need to calculate in with numbers up to 1 billion. Sometimes, I only need to show a rounded whole number. In certain situations, I may need to display 1 decimal places. – Village Dec 6 '11 at 16:12

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

\documentclass{article}
\usepackage{calc}
\newcounter{z}
\newcommand{\printpercent}{%
\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{\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{\FPeval\result{round(#1*100/#2,1)}\result\%}
\begin{document}
\printpercent{2.3}{100}
\printpercent{176.5}{190.375}
\end{document}


Another possibility is to use pgfmath with siunitx. I'm not sure that the precision is always correct, in this case it's possible to use fpuor fp.

update : For a user who works with tikz it's possible to replace SI by \pgfmathprintnumber

\documentclass{article}

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

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

\begin{document}
\printpercent{1}{100}
\printpercent{200}{250}
\printpercent{2}{3}
\end{document} • Was that the intention of the siunitx package to place a space between the number and percent symbol? – Village Dec 7 '11 at 21:46