[Tex/LaTex] Parse simple arithmetics and return the result

calculationsprogramming

I want a command \ca which takes a simple arithmetic calculation as an argument and returns the result with proper decimal places. Additionally I want an boolean argument which decides if only the result is printed or the whole calculation.

For example

\ca{8.12 - 2.2 + 1}

should just print 6.92.

or

\ca[t]{8.12 - 2.2 + 1}

should print 8.12 – 2.2 + 1 = 6.92

Following the question How can I sum two values and store the result in other variable? I did this:

\documentclass{article}
\usepackage[nomessages]{fp}% http://ctan.org/pkg/fp
\usepackage{ifthen}

\newcommand{\ca}[2][f]{
\FPeval{\result}{clip(#2)}
\ifthenelse{\equal{#1}{t}}{
$#2=  \result$}
{
\result
}
}



\begin{document}
\ca[t]{3*(2.2 + 2.3)}

\ca{2.5 + 2.78}
\end{document}

Is it possible to to the same such that the german comma notation is used in what is displayed (i.e. 8,2 instead of 8.2) and in the case the calculation is printed that * is printed as \dcot.

Best Answer

Here is a crude way of modifying the output to be \cdot and ,-specific using xstring. The reason for using xstring is because the argument to fp (#2) would otherwise have to be parsed and separated into operators and operands to enable numprint usage (say).

enter image description here

\documentclass{article}
\usepackage[nomessages]{fp}% http://ctan.org/pkg/fp
\usepackage{xstring}% http://ctan.org/pkg/xstring
\usepackage{xparse}% http://ctan.org/pkg/xparse

\NewDocumentCommand{\ca}{s m}{
  \FPeval{\result}{clip(#2)}
  \IfBooleanTF{#1}% Condition on starred/unstarred version
    {% starred version \ca*{...}
      \StrSubstitute{\result}{.}{,}
    }{% unstarred version \ca{...}
      \StrSubstitute{#2}{.}{,\!}[\temp]% '.' -> ','
      \StrSubstitute{\temp}{*}{\cdot}[\temp]% '*' -> '\cdot'
      $\temp=\StrSubstitute{\result}{.}{,\!}$
    }
}

\begin{document}
\ca{3*(2.2 + 2.3)}

\ca*{2.5 + 2.78}
\end{document}​

xparse was used to provide a starred/unstarred version of \ca where the unstarred version \ca prints the expression, while the starred version \ca* does not.

Related Question