[Tex/LaTex] How to sum two values and store the result in other variable

calculationsdimension-expressions

In LaTeX2e,how can I sum two values and assign them to other variable?

I want to compute something like:

var=\textwidth - 1cm 

And if both were constants:

var=1+1

Best Answer

In regular LaTeX, the calc package allows for easy manipulation of length arithmetic:

\documentclass{article}
\usepackage{calc}% http://ctan.org/pkg/calc
\newlength{\mylength}
\begin{document}
\setlength{\mylength}{\textwidth}%
\noindent\rule{\mylength}{20pt}

\bigskip
\setlength{\mylength}{\textwidth-1cm}%
\noindent\rule{\mylength}{20pt}

\bigskip
\setlength{\mylength}{\textwidth-80pt+5mm-1bp}%
\noindent\rule{\mylength}{20pt}
\end{document}

Lines of different lengths using calc package

The above deals with lengths. For basic arithmetic using numbers, the fp package. Here is an example using infix notation (Reverse Polish Notation/RPN is also possible via \FPupn):

\documentclass{article}
\usepackage[nomessages]{fp}% http://ctan.org/pkg/fp
\begin{document}
The following arithmetic is easy:
\begin{itemize}
  \item \FPeval{\result}{clip(5+6)}%
    $5+6=\result$
  \item \FPeval{\result}{round(2+3/5*pi,5)}%
    $2+3/5\times\pi=\result$
\end{itemize}
\end{document}

Regular arithmetic using fp package