[Tex/LaTex] Using LaTeX as calculator

calculationsfp

I know that exist several packages, like fp that allow to make all kinds of computations.

But I do not understand the correct way to use them.

I need some simple examples of multiplication and division.

I would like compute some data and output them with a custom .sty file.

An Example is:

Italy = 800 000 km of roads (by wikipedia)

SRS = 14 839.9 km (the paths of the project)

SRSpercent = SRS / Italy * 100

And I would like that Italy and SRS as the input variables, SRSpercent as one of the output variables.

I need this so that I do not have to rewrite the numbers in the papers every day.

Best Answer

Here's a solution that uses LuaLaTeX. No additional floating-point routines need be loaded. The output precision is controlled by the first argument of the string.format function; in the example below, the code is set to show 3 digits after the decimal marker.

enter image description here

% !TEX TS-program = lualatex   %% needs LuaLaTeX format
\documentclass{article}
\usepackage{luacode}  % for "\luaexec" macro 
\newcommand\mycalc[1]{%
     \luaexec{ tex.sprint ( string.format( "\%.3f" , #1 ) )}}

\begin{document}
\newcommand{\ItalyRoads}{800000}
\newcommand{\SRSroads}{14839.9}
\newcommand{\SRSpercent}{\mycalc{\SRSroads/\ItalyRoads*100}}

The value of \verb+\SRSpercent+ is \SRSpercent\%.
\end{document}
Related Question