# Can LaTeX perform simple math operations? [duplicate]

Possible Duplicate:
How can I automatically calculate sums in a LaTeX table?

Can LaTeX do simple math?

I have a table with two columns and want to automatically add a third column which contains the difference between the two first:

+------+------+-------+
|  M1  |  M2  | M2-M1 |
+------+------+-------+
| 80.1 | 95.2 | +15.1 |
+ ...  | ...  |  ...  |


I could write a Perl script that generates the third column but it would also be nice if LaTeX could do that directly ...

-

## marked as duplicate by Martin Scharrer♦Apr 6 '11 at 14:23

Possible duplicate: http://tex.stackexchange.com/q/3851/1235. –  Hendrik Vogt Jan 11 '11 at 11:05
Since you have some responses below that seem to answer your question, please consider marking one of them as ‘Accepted’ by clicking on the tickmark below their vote count. Please also take a look at the question that Hendrik has suggested as the answers there might help you. If they do, that's great, and we'll probably close this question as a duplicate just to keep the place tidy and to help people find the answers quickly. If they don't, please edit your question here to explain why so that people can better focus their attention to help you. –  Martin Scharrer Apr 2 '11 at 11:35

Herbert and Alexander already mentioned spreadtab. Here's a simple way to do it without using it.

\documentclass{article}
\usepackage{booktabs}
\usepackage{fp}
\begin{document}
\def\printnum#1{%
\expandafter\printnumaux#1\relax
}
\def\printnumaux#1.#2#3\relax{%
$\ifnum#1>0+\fi#1.#2$%
}
\def\row#1#2{#1&#2&\FPsub\r{#2}{#1}\printnum\r\\}
\begin{tabular}{rrr}
\toprule
M1&M2&M2$-$M1\\
\midrule
\row{80.1}{95.2}
\row{37.2}{73.1}
\bottomrule
\end{tabular}
\end{document}


The \row macro takes two arguments and makes the three columns you want. The subtraction is done by the fp package and the number formatting is done by the \printnum macro.

-
@TH you can also use FPround if you do not want to load another package. –  Yiannis Lazarides Jan 11 '11 at 11:02
@Yiannis: I'm not sure how that avoids loading another package, but \FPround does seem like a good idea. –  TH. Jan 11 '11 at 11:25
@TH Sorry I thought you used the numprint package as well! Read your post too quick and did not notice that you defined your own macro for formatting! –  Yiannis Lazarides Jan 11 '11 at 13:40

I don't know an easy way to add a third column »automatically«. Maybe you draft the third column yourself and make LaTeX add the content.

This can be done with spreadtab, but much better by using LuaTeX.

-

you can do it easily with package spreadtab

-