8

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

Andrew Swann
  • 95,762
Simeon Simeonov
  • 819
  • 5
  • 11
  • 6
    Welcome to TeX.SE. It would be helpful if you composed a fully compilable MWE including \documentclass and the appropriate packages that sets up the problem. While solving problems can be fun, setting them up is not. Then, those trying to help can simply cut and paste your MWE and get started on solving the problem. – Peter Grill Nov 15 '18 at 07:46
  • 1
    yes, it is possible (to align to where you like to have). for example by use of an ąrray or atabular`. but first show us, what you try so far. – Zarko Nov 15 '18 at 07:54
  • Is your question purely about typesetting, or is it also about performing the summation operations? – Mico Nov 15 '18 at 08:06
  • Duplicate? https://tex.stackexchange.com/questions/337840/how-do-i-typeset-multiple-additions-nicely, https://tex.stackexchange.com/questions/11702/how-to-present-a-vertical-multiplication-addition, https://tex.stackexchange.com/questions/219090/writing-manual-summation-of-two-numbers – Steven B. Segletes Nov 15 '18 at 10:29

4 Answers4

9

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. –  Nov 15 '18 at 10:34
8

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 https://tex.stackexchange.com/questions/88472/consistant-formatting-with-siunitx-and-pgf-thousands-separator/88474 --- you need \sisetup{group-four-digits=true} or something similar... – Rmano Nov 15 '18 at 09:09
  • @Rmano That question doesn't seem to be relevant as it is asking about having siunitx-like output using pgfmath. –  Nov 15 '18 at 09:12
  • 3
    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 '18 at 09:15
7

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

egreg
  • 1,121,712
7

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}
Mico
  • 506,678
  • 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) –  Nov 15 '18 at 09:32
  • 1
    (\count0=#2\relax\advance\count0by#3\relax\the\count0\relax) –  Nov 15 '18 at 09:35
  • 2
    @jfbu - But where's the fun if I can't use \directlua and tex.sprint? :-) – Mico Nov 15 '18 at 09: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... :) –  Nov 15 '18 at 09: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:) –  Nov 15 '18 at 09:51
  • 1
    Simple syntax unlike the LaTeX3 syntax :) – Salim Bou Nov 15 '18 at 12:03
  • @SalimBou - Thanks. :-) What makes the syntax particularly simple is that I'm only allowing two summands -- as that's what the OP indicated he/she wanted to achieve. The other answers are all allowing multiple summands; that's what's making their code a lot more complex. Let's see if the OP speaks up and expresses a desire to allow more than two summands. For sure, the Lua-based code would have to become slightly more complex if I had to extend the answer in this manner. However, it would likely stilly be simpler than that of the LaTeX3-based solutions... – Mico Nov 15 '18 at 13:09