I need to make many of these. If it s possible numbers to be aligned right. How to do that?enter image description here

up vote 8 down vote accepted

A no-package approach for three term or higher sums as well.

\documentclass{article}

\newcommand{\showsum}[2][c]{%
  $\edef\originalplusmathcode{\the\mathcode`+}%
   \begingroup\lccode`~=`+ \lowercase{\endgroup\def~}{\\&}%
   \mathcode`+ "8000
  \begin{array}[#1]{@{}r@{\;}r@{}}
   \mathchar\originalplusmathcode& #2 \\
  \hline
  & \the\numexpr#2\relax
  \end{array}%
  $%
 }

\begin{document}

X\quad % to show the baseline
\showsum{12345 + 6543}\quad
\showsum{521725 + 256814}\quad
\showsum{523057 + 6743}\quad
\showsum[t]{57208+6207}\quad
\showsum[b]{57208+6207+12095}\quad
X

\end{document}

enter image description here

The X are here to indicate baseline. (plagiarized from @egreg)


Variant display:

\documentclass{article}

\newcommand{\showsum}[2][c]{%
  $\edef\originalplusmathcode{\the\mathcode`+}%
   \begingroup\lccode`~=`+ \lowercase{\endgroup\def~}{\\\mathchar\originalplusmathcode&}%
   \mathcode`+ "8000
  \begin{array}[#1]{@{}r@{\;}r@{}}
   & #2 \\
  \hline
  =& \the\numexpr#2\relax
  \end{array}%
  $%
 }

\begin{document}

X\quad % to show the baseline
\showsum{12345 + 6543}\quad
\showsum{521725 + 256814}\quad
\showsum{523057 + 6743}\quad
\showsum[t]{57208+6207+77777}\quad
\showsum[b]{57208+6207+12095+33333}\quad
X

\end{document}

enter image description here


We can also sum negative integers:

\documentclass{article}

\newcommand{\showsum}[2][c]{%
  $\edef\originalplusmathcode{\the\mathcode`+}%
   \begingroup\lccode`~=`+ \lowercase{\endgroup\def~}{\\\mathchar\originalplusmathcode&}%
   \edef\originalminusmathcode{\the\mathcode`-}%
   \begingroup\lccode`~=`- \lowercase{\endgroup\def~}{\\\mathchar\originalminusmathcode&}%
   \mathcode`+ "8000
   \mathcode`- "8000
  \begin{array}[#1]{@{}r@{\;}r@{}}
   & #2 \\
  \hline
  =& \the\numexpr#2\relax
  \end{array}%
  $%
 }

\begin{document}

X\quad % to show the baseline
\showsum{12345 - 6543}\quad
\showsum{521725 + 256814}\quad
\showsum{523057 - 6743}\quad
\showsum[t]{57208-6207+77777}\quad
\showsum[b]{57208-6207+12095-33333}\quad
X

\end{document}

enter image description here

(there was a missing % after the final $ in all three \showsum, fixed now but images not updated)

  • 1
    I have often dreamt about an extension of TeX of "mathematically active" to more general "quasi-active" even outside math mode, which would be active characters except in \edef, \csname...\endcsname, or \numexpr...\relax context, like mathematically active characters are (my answer demonstrates it). Such "quasi-active" characters (keeping the same catcode) would be very useful. – jfbu Nov 15 at 10:34

The code below defines a macro, \Summation, that accepts a comma separated list of integers such as

  \Summation{12345, 6543}
  \Summation{521725, 256814}
  \Summation{523057, 6743}
  \Summation{57208,6207}
  \Summation[b]{57208,6207,12095}

The macro then adds the integers in a table, as in the OP. The commands above give the output:

enter image description here

There is an optional first argument that becomes the positioning optional argument in the tabular environment (by default, t is used). I haven't really checked, but it is likely ro break with large integers.

All of the integers are printed using the \num command from the siunitx package, so their formatting can be customised using siunitx. for example, by adding

\sisetup{group-separator={,},group-four-digits}

the numbers will have a comma separating the thousands, millions, ... etc. so that the output becomes

enter image description here

The code is an exercise in using LaTeX3:

\documentclass{article}
\usepackage{xparse}
\usepackage{siunitx}

\ExplSyntaxOn
\clist_new:N \l_int_clist
\int_new:N \g_total_int
\tl_new:N \g_summation_tl
\NewDocumentCommand\Summation {O{t} m}{
  \clist_set:Nn \l_int_clist {#2}
  \int_zero:N \g_total_int
  \tl_clear:N \g_summation_tl
  \clist_map_inline:Nn \l_int_clist {
    \int_gadd:Nn \g_total_int {##1}
    \tl_gput_right:No \g_summation_tl {& \num{##1}\\}
   }
   \begin{tabular}[#1]{r@{\space}r}
     + \tl_use:N \g_summation_tl \cline{2-2}
     &\num{\int_use:N \g_total_int}
  \end{tabular}
}
\ExplSyntaxOff

\begin{document}

  \Summation{12345, 6543}
  \Summation{521725, 256814}
  \Summation{523057, 6743}
  \Summation{57208,6207}
  \Summation[b]{57208,6207,12095}

\end{document}

As noted in Latex3 inline mapping produces extra row in tabular, it is necessary to construct the table as a token list because otherwise \hrule will complain.

  • 1
    hmmm... look at tex.stackexchange.com/questions/88472/… --- you need \sisetup{group-four-digits=true} or something similar... – Rmano Nov 15 at 9:09
  • @Rmano That question doesn't seem to be relevant as it is asking about having siunitx-like output using pgfmath. – Andrew Nov 15 at 9:12
  • 2
    Yes, but look at your example: 12345 has a thousand separator but 6543 no, so the 2 and the 6 don't align. You have to force siunitx to add the separator also for 4-figures numbers... – Rmano Nov 15 at 9:15
  • @Rmano Ah, OK, thanks! I have added this. – Andrew Nov 15 at 9:17

Let TeX do the calculations

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\showsum}{O{c}m}
 {
  \ensuremath
   {
    \simeon_showsum:nn { #1 } { #2 }
   }
 }

\seq_new:N \l__simeon_showsum_seq

\cs_new_protected:Nn \simeon_showsum:nn
 {
  \seq_set_split:Nnn \l__simeon_showsum_seq { + } { #2 }
  \begin{array}[#1]{@{}r@{\;}r@{}}
  + & \seq_use:Nn \l__simeon_showsum_seq { \\ & } \\
  \hline
  & \int_eval:n { #2 }
  \end{array}
 }
\ExplSyntaxOff

\begin{document}

X\quad % to show the baseline
\showsum{12345 + 6543}\quad
\showsum{521725 + 256814}\quad
\showsum{523057 + 6743}\quad
\showsum[t]{57208+6207}\quad
\showsum[b]{57208+6207+12095}\quad
X

\end{document}

enter image description here

  • Since you're using + as the separator you could use \int_eval:n { #2 } instead of \int_eval:n { \seq_use:Nn \l__simeon_showsum_seq { + } }. – Andrew Nov 15 at 9:32
  • @Andrew indeed! – egreg Nov 15 at 10:03

Here's a LuaLaTeX-based solution. The macro \mysum takes two mandatory arguments -- the numbers to be summed -- and one optional argument, which determines how the array environment should be placed vertically relative to the math baseline: centered (the default), top-aligned, or bottom-aligned. (If an optional argument is set, it must be listed first and enclosed in square brackets, per the usual LaTeX macro syntax rules.)

enter image description here

\documentclass{article}
\usepackage{booktabs} % for "\midrule" macro
\newcommand{\mysum}[3][c]{%
   \begin{array}[#1]{@{}r@{}}
      #2 \\ {+}\: #3 \\ \midrule \directlua{tex.sprint(#2+#3)}
   \end{array}}
\usepackage{newtxtext,newtxmath} % optional (Times Roman text and math fonts)
\begin{document}
\[
\mysum{12345}{6543}       \qquad
\mysum{511725}{256814}    \qquad
\mysum[b]{523057}{6743}   \qquad
\mysum[t]{57208}{6207}
\]
\end{document}

Addendum to allow for an arbitrary number of summands rather than exactly two summands. The preceding code dealt with the case provided in the original query, which involved exactly two terms in the summation. The following solution, which is still LuaLaTeX-based, allows for an arbitrary number of summarnds. It works as follows:

  • The LaTeX macro \mysum takes one optional argument (the vertical placement indicator, see above) and one mandatory argument: a string of comma-separated numbers. Whitespace is allowed inside the string. Thus, \mysum{12345,6543}, \mysum{12345, 6543}, \mysum{ 12345 , 6543 }, and \mysum{12345,6543 }, are all equally valid -- and produce the same output, viz., the number 18888.

  • The \mysum macro performs the following tasks: It sets up an array environment, calls the Lua function perform_summation to perform most of the actual work, and terminates the array environment.

  • The perform_summation Lua function begins by splitting the comma-delimited string of numbers into a Lua table, using , as the separator. (The auxiliary function that performs the splitting was obtained from stackoverflow.) perform_summation then iterates over the table entries to (a) compute the running subtotal of the entries and (b) print out each entry on a separate row. Finally, the Lua function prints the value of the sum of the entries.

The 3 "-" symbols located at the left-hand and right-hand edges of the following screenshot merely serve to indicate the location of the math axis.

enter image description here

\documentclass{article}
\usepackage{newtxtext,newtxmath} % optional: Times Roman text and math fonts
\usepackage{booktabs} % for "\midrule" macro
\usepackage{luacode}  % for "luacode" environment

%% Lua-side code:
\begin{luacode}
-- The following code is from https://stackoverflow.com/a/19263313:
function string:split( inSplitPattern )
  outResults = { }
  local theStart = 1
  local theSplitStart, theSplitEnd = string.find( self, inSplitPattern, theStart )
  while theSplitStart do
    table.insert( outResults, string.sub( self, theStart, theSplitStart-1 ) )
    theStart = theSplitEnd + 1
    theSplitStart, theSplitEnd = string.find( self, inSplitPattern, theStart )
  end
  table.insert( outResults, string.sub( self, theStart ) )
  return outResults
end

function perform_summation ( s )
  t = s:split(",")
  sum = 0 -- initialize "sum" variable
  tex.sprint ( "+\\:" ) -- print the "+" symbol
  for i=1,#t do
    sum = sum+t[i]
    tex.sprint ( t[i] .. "\\\\" )
  end
  tex.sprint ( "\\midrule" .. sum )
end
\end{luacode}

%% LaTeX-side code:
\newcommand{\mysum}[2][c]{%
   \begin{array}[#1]{@{}r@{}}
      \directlua{perform_summation("#2")}
   \end{array}}

\begin{document}
\[
---\quad  % indicate math axis
\mysum{12345,6543}       \qquad
\mysum{1234567891234,9876543219877} \qquad
\mysum{1,2,3,4} \qquad
\mysum[t]{ 57208 , 6207 , 12095 } \qquad
\mysum[b]{12345,67890}
\quad---{}   % indicate math axis
\]
\end{document}
  • 1
    \the\numexpr#2+#3\relax will work fine with numbers having a sum not exceeding 2147483647.... (and it is not even needed to use \numexpr, TeX non-expandable arithmetic would be fine too) – jfbu Nov 15 at 9:32
  • 1
    (\count0=#2\relax\advance\count0by#3\relax\the\count0\relax) – jfbu Nov 15 at 9:35
  • 2
    @jfbu - But where's the fun if I can't use \directlua and tex.sprint? :-) – Mico Nov 15 at 9:37
  • 1
    I did suspect something like that and in view of the tremendous number of answers I have myself provided with xint I can sympathize... :) – jfbu Nov 15 at 9:43
  • 1
    @jfbu When I posted my answer I assumed that it was only a matter of time before you posted a really quick xint solution that would also work for large integers:) I didn't think of lualatex (+1)...another thing to learn:) – Andrew Nov 15 at 9:51

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.