3

I have to deal with a lot of numbers in my latex documents. So far, I have been using a rudimentary \newcommand{\VarOne}{1000} to define \VarOne and then use it as it is using \VarOne{} in the document.

Can I use LaTeX to perform basic operations like add/ subtract/ multiply/ divide numbers --- integers/ non-integers?

Also, is there a way to print non-integers with comma separated values? So, \newcommand{\VarOne}{1000.97} produces 1,000.97 when used in the document? I can do this only for integers using \newcommand\mynum[1]{\num[group-separator={,},group-minimum-digits=4]{\the\numexpr(#1)\relax}} macro.

Werner
  • 603,163
deshmukh
  • 2,435
  • 1
  • 26
  • 46

2 Answers2

3

Yes. Here's a LaTeX3 implementation:

\documentclass{article}
\usepackage{expl3, xparse, siunitx}
\ExplSyntaxOn
\NewDocumentCommand { \calcnum } { O{} m }
  { \num [  round-mode=places , round-precision=2 , group-separator={,}, group-minimum-digits=4, #1] { \fp_to_decimal:n {#2} } }
\ExplSyntaxOff
\begin{document}
\calcnum{1000.97}

\newcommand{\VarOne}{1000.97}
\calcnum{\VarOne}

\calcnum{\VarOne+13}

\calcnum{\VarOne + 2*\VarOne / 3 - \VarOne}
\end{document}

Output is

1,000.97
1,000.97
1,013.97
667.31

Werner
  • 603,163
  • Great. One more thing. In India, we group the numbers differently. 900,000 is written as 9,00,000 i.e. after the initial grouping of three digits, all other groups are of two digits. Is there any way this can be done in latex? – deshmukh Nov 27 '14 at 15:48
  • @deshmukh: Most likely there would be, but you'll have to provide a full specification as to where the , goes and when. Then I would suggest you ask a follow-up question (linking back to this question) specifically requesting that formatting. Remember: Be clear in your presentation of exactly the what the formatting should be. – Werner Nov 27 '14 at 16:32
  • 1
    @deshmukh regarding the question in your comment it has been asked at https://tex.stackexchange.com/questions/144976/grouping-digits-according-to-the-indian-numbering-system-in-siunitx and got an answer at https://tex.stackexchange.com/a/145000/4686 –  Jul 27 '17 at 17:41
1

You can use the pgf math engine as well:

enter image description here

Notes:

  • Besides the siunitx's \num macro you can also use \pgfmathprintnumber to control the formatting of numerical results.

Code:

\documentclass{article}
\usepackage{pgfmath}
\usepackage{siunitx}

\newcommand{\calcnum}[1]{% \pgfmathparse{#1}% \num[group-separator={,},group-minimum-digits=4]{\pgfmathresult}% }

\begin{document} \calcnum{1000.97}

\newcommand{\VarOne}{1000.97} \calcnum{\VarOne}

\calcnum{\VarOne+13}

\calcnum{\VarOne + 2*\VarOne / 3 - \VarOne} \end{document}

Peter Grill
  • 223,288
  • Great. One more thing. In India, we group the numbers differently. 900,000 is written as 9,00,000 i.e. after the initial grouping of three digits, all other groups are of two digits. Is there any way this can be done in latex? – deshmukh Nov 27 '14 at 15:49