Calculations on variables using LaTeX
xfp
provides a number of f
loating p
oint operations:
\documentclass{article}
\usepackage{xfp}
\begin{document}
\newcommand{\lengthHeatExchanger}{0.820}
\newcommand{\heightHeatExchanger}{1.081}
\newcommand{\areaHeatExchanger}{\fpeval{\lengthHeatExchanger * \heightHeatExchanger}}
$\verb|\lengthHeatExchanger| = \lengthHeatExchanger$
$\verb|\heightHeatExchanger| = \heightHeatExchanger$
$\verb|\lengthHeatExchanger| \times \verb|\heightHeatExchanger| = \areaHeatExchanger$
\end{document}
If needed, it handles calculations on dimensions by converting it to pt
and managing as a f
loating p
oint without the need to strip the dimension manually.
If you're free to employ LuaLaTeX, performing calculations involving macros doesn't require the loading of any external packages, as the following example shows. The solution method exploits the fact that the argument of \directlua
is expanded automatically. In the current example, \docalc{\length*\height}
is expanded to \directlua{tex.sprint(2.5*4)}
; LuaTeX performs the calculation, and the result (10
) replaces \docalc{\length*\height}
; hence, it works out to \newcommand{\area}{10}
.
Of course, if you needn't store the value of the calculation, you could simply run $\length \times \height = \docalc{\length*\height}$
.
\documentclass{article}
%% The following setup assumes that either pdfLaTeX or LuaLaTeX is in use.
\usepackage{ifluatex} % for '\ifluatex' macro
\ifluatex
\usepackage{unicode-math} % load 'fontspec' package automatically
% use \setmainfont and \setmathfont directives as needed...
% Set up a LaTeX macro to interface with Lua:
\newcommand\docalc[1]{\directlua{tex.sprint(#1)}}
\else % assume that pdfLaTeX is in use
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\fi
% remainder of preamble...
\begin{document}
\newcommand{\length}{2.5}
\newcommand{\height}{4}
\ifluatex
\newcommand{\area}{\docalc{\length*\height}}
$\length \times \height = \area$
\fi
\end{document}
I will suggest to use the calculator
package and its \MULTIPLY
command, see documentation here.
BUT: I think that if you could switch to LuaLaTeX it would surely be the best solution!