Summing numbers like fractions











up vote
7
down vote

favorite
2












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










share|improve this question









New contributor




Simeon Simeonov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 5




    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
    14 hours ago






  • 1




    yes, it is possible (to align to where you like to have). for example by use of an ąrray or a tabular`. but first show us, what you try so far.
    – Zarko
    14 hours ago










  • Is your question purely about typesetting, or is it also about performing the summation operations?
    – Mico
    14 hours ago










  • Duplicate? tex.stackexchange.com/questions/337840/…, tex.stackexchange.com/questions/11702/…, tex.stackexchange.com/questions/219090/…
    – Steven B. Segletes
    12 hours ago

















up vote
7
down vote

favorite
2












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










share|improve this question









New contributor




Simeon Simeonov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 5




    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
    14 hours ago






  • 1




    yes, it is possible (to align to where you like to have). for example by use of an ąrray or a tabular`. but first show us, what you try so far.
    – Zarko
    14 hours ago










  • Is your question purely about typesetting, or is it also about performing the summation operations?
    – Mico
    14 hours ago










  • Duplicate? tex.stackexchange.com/questions/337840/…, tex.stackexchange.com/questions/11702/…, tex.stackexchange.com/questions/219090/…
    – Steven B. Segletes
    12 hours ago















up vote
7
down vote

favorite
2









up vote
7
down vote

favorite
2






2





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










share|improve this question









New contributor




Simeon Simeonov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











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







tables macros






share|improve this question









New contributor




Simeon Simeonov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Simeon Simeonov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 13 hours ago









Andrew

29.2k34177




29.2k34177






New contributor




Simeon Simeonov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 15 hours ago









Simeon Simeonov

444




444




New contributor




Simeon Simeonov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Simeon Simeonov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Simeon Simeonov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








  • 5




    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
    14 hours ago






  • 1




    yes, it is possible (to align to where you like to have). for example by use of an ąrray or a tabular`. but first show us, what you try so far.
    – Zarko
    14 hours ago










  • Is your question purely about typesetting, or is it also about performing the summation operations?
    – Mico
    14 hours ago










  • Duplicate? tex.stackexchange.com/questions/337840/…, tex.stackexchange.com/questions/11702/…, tex.stackexchange.com/questions/219090/…
    – Steven B. Segletes
    12 hours ago
















  • 5




    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
    14 hours ago






  • 1




    yes, it is possible (to align to where you like to have). for example by use of an ąrray or a tabular`. but first show us, what you try so far.
    – Zarko
    14 hours ago










  • Is your question purely about typesetting, or is it also about performing the summation operations?
    – Mico
    14 hours ago










  • Duplicate? tex.stackexchange.com/questions/337840/…, tex.stackexchange.com/questions/11702/…, tex.stackexchange.com/questions/219090/…
    – Steven B. Segletes
    12 hours ago










5




5




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
14 hours ago




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
14 hours ago




1




1




yes, it is possible (to align to where you like to have). for example by use of an ąrray or a tabular`. but first show us, what you try so far.
– Zarko
14 hours ago




yes, it is possible (to align to where you like to have). for example by use of an ąrray or a tabular`. but first show us, what you try so far.
– Zarko
14 hours ago












Is your question purely about typesetting, or is it also about performing the summation operations?
– Mico
14 hours ago




Is your question purely about typesetting, or is it also about performing the summation operations?
– Mico
14 hours ago












Duplicate? tex.stackexchange.com/questions/337840/…, tex.stackexchange.com/questions/11702/…, tex.stackexchange.com/questions/219090/…
– Steven B. Segletes
12 hours ago






Duplicate? tex.stackexchange.com/questions/337840/…, tex.stackexchange.com/questions/11702/…, tex.stackexchange.com/questions/219090/…
– Steven B. Segletes
12 hours ago












4 Answers
4






active

oldest

votes

















up vote
7
down vote













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
NewDocumentCommandSummation {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.






share|improve this answer



















  • 1




    hmmm... look at tex.stackexchange.com/questions/88472/… --- you need sisetup{group-four-digits=true} or something similar...
    – Rmano
    13 hours ago












  • @Rmano That question doesn't seem to be relevant as it is asking about having siunitx-like output using pgfmath.
    – Andrew
    13 hours ago






  • 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
    13 hours ago












  • @Rmano Ah, OK, thanks! I have added this.
    – Andrew
    13 hours ago


















up vote
6
down vote













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



documentclass{article}

newcommand{showsum}[2][c]{%
$edeforiginalplusmathcode{themathcode`+}%
begingrouplccode`~=`+ lowercase{endgroupdef~}{\&}%
mathcode`+ "8000
begin{array}[#1]{@{}r@{;}r@{}}
mathcharoriginalplusmathcode& #2 \
hline
& thenumexpr#2relax
end{array}%
$%
}

begin{document}

Xquad % 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]{%
$edeforiginalplusmathcode{themathcode`+}%
begingrouplccode`~=`+ lowercase{endgroupdef~}{\mathcharoriginalplusmathcode&}%
mathcode`+ "8000
begin{array}[#1]{@{}r@{;}r@{}}
& #2 \
hline
=& thenumexpr#2relax
end{array}%
$%
}

begin{document}

Xquad % 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]{%
$edeforiginalplusmathcode{themathcode`+}%
begingrouplccode`~=`+ lowercase{endgroupdef~}{\mathcharoriginalplusmathcode&}%
edeforiginalminusmathcode{themathcode`-}%
begingrouplccode`~=`- lowercase{endgroupdef~}{\mathcharoriginalminusmathcode&}%
mathcode`+ "8000
mathcode`- "8000
begin{array}[#1]{@{}r@{;}r@{}}
& #2 \
hline
=& thenumexpr#2relax
end{array}%
$%
}

begin{document}

Xquad % 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)






share|improve this answer



















  • 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
    12 hours ago


















up vote
6
down vote













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 an arbitrary number of summands. The preceding code dealt with the case outlined in the original query, which involved exactly two terms in the summation. The following solution, which is still LuaLaTeX-based, works as follows:




  • The LaTeX macro mysum takes one optional argument (the position 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 sets up an array environment, calls the Lua function perform_summation to perform most of the actual work, and terminates the array.



  • The perform_summation 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 sum of the entries and (b) print out each entry on a separate row. Finally, it prints the value of the sum of the entries.



    It is entirely valid, from a syntactic point of view, to execute mysum with just one entry, e.g., mysum{10}.




In the following screenshot, the 3 - symbols at the left-hand and right-hand edged 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}


-- Obtained from https://stackoverflow.com/a/19263313
function string:split( inSplitPattern, outResults )
if not outResults then
outResults = { }
end
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}





share|improve this answer



















  • 1




    thenumexpr#2+#3relax 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
    13 hours ago








  • 1




    (count0=#2relaxadvancecount0by#3relaxthecount0relax)
    – jfbu
    13 hours ago






  • 2




    @jfbu - But where's the fun if I can't use directlua and tex.sprint? :-)
    – Mico
    13 hours ago






  • 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
    12 hours ago








  • 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
    12 hours ago


















up vote
5
down vote













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}

Xquad % 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






share|improve this answer























  • 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
    13 hours ago










  • @Andrew indeed!
    – egreg
    12 hours ago











Your Answer








StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "85"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});






Simeon Simeonov is a new contributor. Be nice, and check out our Code of Conduct.










 

draft saved


draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2ftex.stackexchange.com%2fquestions%2f460078%2fsumming-numbers-like-fractions%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























4 Answers
4






active

oldest

votes








4 Answers
4






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
7
down vote













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
NewDocumentCommandSummation {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.






share|improve this answer



















  • 1




    hmmm... look at tex.stackexchange.com/questions/88472/… --- you need sisetup{group-four-digits=true} or something similar...
    – Rmano
    13 hours ago












  • @Rmano That question doesn't seem to be relevant as it is asking about having siunitx-like output using pgfmath.
    – Andrew
    13 hours ago






  • 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
    13 hours ago












  • @Rmano Ah, OK, thanks! I have added this.
    – Andrew
    13 hours ago















up vote
7
down vote













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
NewDocumentCommandSummation {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.






share|improve this answer



















  • 1




    hmmm... look at tex.stackexchange.com/questions/88472/… --- you need sisetup{group-four-digits=true} or something similar...
    – Rmano
    13 hours ago












  • @Rmano That question doesn't seem to be relevant as it is asking about having siunitx-like output using pgfmath.
    – Andrew
    13 hours ago






  • 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
    13 hours ago












  • @Rmano Ah, OK, thanks! I have added this.
    – Andrew
    13 hours ago













up vote
7
down vote










up vote
7
down vote









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
NewDocumentCommandSummation {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.






share|improve this answer














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
NewDocumentCommandSummation {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.







share|improve this answer














share|improve this answer



share|improve this answer








edited 13 hours ago

























answered 13 hours ago









Andrew

29.2k34177




29.2k34177








  • 1




    hmmm... look at tex.stackexchange.com/questions/88472/… --- you need sisetup{group-four-digits=true} or something similar...
    – Rmano
    13 hours ago












  • @Rmano That question doesn't seem to be relevant as it is asking about having siunitx-like output using pgfmath.
    – Andrew
    13 hours ago






  • 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
    13 hours ago












  • @Rmano Ah, OK, thanks! I have added this.
    – Andrew
    13 hours ago














  • 1




    hmmm... look at tex.stackexchange.com/questions/88472/… --- you need sisetup{group-four-digits=true} or something similar...
    – Rmano
    13 hours ago












  • @Rmano That question doesn't seem to be relevant as it is asking about having siunitx-like output using pgfmath.
    – Andrew
    13 hours ago






  • 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
    13 hours ago












  • @Rmano Ah, OK, thanks! I have added this.
    – Andrew
    13 hours ago








1




1




hmmm... look at tex.stackexchange.com/questions/88472/… --- you need sisetup{group-four-digits=true} or something similar...
– Rmano
13 hours ago






hmmm... look at tex.stackexchange.com/questions/88472/… --- you need sisetup{group-four-digits=true} or something similar...
– Rmano
13 hours ago














@Rmano That question doesn't seem to be relevant as it is asking about having siunitx-like output using pgfmath.
– Andrew
13 hours ago




@Rmano That question doesn't seem to be relevant as it is asking about having siunitx-like output using pgfmath.
– Andrew
13 hours ago




2




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
13 hours ago






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
13 hours ago














@Rmano Ah, OK, thanks! I have added this.
– Andrew
13 hours ago




@Rmano Ah, OK, thanks! I have added this.
– Andrew
13 hours ago










up vote
6
down vote













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



documentclass{article}

newcommand{showsum}[2][c]{%
$edeforiginalplusmathcode{themathcode`+}%
begingrouplccode`~=`+ lowercase{endgroupdef~}{\&}%
mathcode`+ "8000
begin{array}[#1]{@{}r@{;}r@{}}
mathcharoriginalplusmathcode& #2 \
hline
& thenumexpr#2relax
end{array}%
$%
}

begin{document}

Xquad % 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]{%
$edeforiginalplusmathcode{themathcode`+}%
begingrouplccode`~=`+ lowercase{endgroupdef~}{\mathcharoriginalplusmathcode&}%
mathcode`+ "8000
begin{array}[#1]{@{}r@{;}r@{}}
& #2 \
hline
=& thenumexpr#2relax
end{array}%
$%
}

begin{document}

Xquad % 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]{%
$edeforiginalplusmathcode{themathcode`+}%
begingrouplccode`~=`+ lowercase{endgroupdef~}{\mathcharoriginalplusmathcode&}%
edeforiginalminusmathcode{themathcode`-}%
begingrouplccode`~=`- lowercase{endgroupdef~}{\mathcharoriginalminusmathcode&}%
mathcode`+ "8000
mathcode`- "8000
begin{array}[#1]{@{}r@{;}r@{}}
& #2 \
hline
=& thenumexpr#2relax
end{array}%
$%
}

begin{document}

Xquad % 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)






share|improve this answer



















  • 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
    12 hours ago















up vote
6
down vote













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



documentclass{article}

newcommand{showsum}[2][c]{%
$edeforiginalplusmathcode{themathcode`+}%
begingrouplccode`~=`+ lowercase{endgroupdef~}{\&}%
mathcode`+ "8000
begin{array}[#1]{@{}r@{;}r@{}}
mathcharoriginalplusmathcode& #2 \
hline
& thenumexpr#2relax
end{array}%
$%
}

begin{document}

Xquad % 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]{%
$edeforiginalplusmathcode{themathcode`+}%
begingrouplccode`~=`+ lowercase{endgroupdef~}{\mathcharoriginalplusmathcode&}%
mathcode`+ "8000
begin{array}[#1]{@{}r@{;}r@{}}
& #2 \
hline
=& thenumexpr#2relax
end{array}%
$%
}

begin{document}

Xquad % 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]{%
$edeforiginalplusmathcode{themathcode`+}%
begingrouplccode`~=`+ lowercase{endgroupdef~}{\mathcharoriginalplusmathcode&}%
edeforiginalminusmathcode{themathcode`-}%
begingrouplccode`~=`- lowercase{endgroupdef~}{\mathcharoriginalminusmathcode&}%
mathcode`+ "8000
mathcode`- "8000
begin{array}[#1]{@{}r@{;}r@{}}
& #2 \
hline
=& thenumexpr#2relax
end{array}%
$%
}

begin{document}

Xquad % 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)






share|improve this answer



















  • 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
    12 hours ago













up vote
6
down vote










up vote
6
down vote









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



documentclass{article}

newcommand{showsum}[2][c]{%
$edeforiginalplusmathcode{themathcode`+}%
begingrouplccode`~=`+ lowercase{endgroupdef~}{\&}%
mathcode`+ "8000
begin{array}[#1]{@{}r@{;}r@{}}
mathcharoriginalplusmathcode& #2 \
hline
& thenumexpr#2relax
end{array}%
$%
}

begin{document}

Xquad % 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]{%
$edeforiginalplusmathcode{themathcode`+}%
begingrouplccode`~=`+ lowercase{endgroupdef~}{\mathcharoriginalplusmathcode&}%
mathcode`+ "8000
begin{array}[#1]{@{}r@{;}r@{}}
& #2 \
hline
=& thenumexpr#2relax
end{array}%
$%
}

begin{document}

Xquad % 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]{%
$edeforiginalplusmathcode{themathcode`+}%
begingrouplccode`~=`+ lowercase{endgroupdef~}{\mathcharoriginalplusmathcode&}%
edeforiginalminusmathcode{themathcode`-}%
begingrouplccode`~=`- lowercase{endgroupdef~}{\mathcharoriginalminusmathcode&}%
mathcode`+ "8000
mathcode`- "8000
begin{array}[#1]{@{}r@{;}r@{}}
& #2 \
hline
=& thenumexpr#2relax
end{array}%
$%
}

begin{document}

Xquad % 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)






share|improve this answer














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



documentclass{article}

newcommand{showsum}[2][c]{%
$edeforiginalplusmathcode{themathcode`+}%
begingrouplccode`~=`+ lowercase{endgroupdef~}{\&}%
mathcode`+ "8000
begin{array}[#1]{@{}r@{;}r@{}}
mathcharoriginalplusmathcode& #2 \
hline
& thenumexpr#2relax
end{array}%
$%
}

begin{document}

Xquad % 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]{%
$edeforiginalplusmathcode{themathcode`+}%
begingrouplccode`~=`+ lowercase{endgroupdef~}{\mathcharoriginalplusmathcode&}%
mathcode`+ "8000
begin{array}[#1]{@{}r@{;}r@{}}
& #2 \
hline
=& thenumexpr#2relax
end{array}%
$%
}

begin{document}

Xquad % 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]{%
$edeforiginalplusmathcode{themathcode`+}%
begingrouplccode`~=`+ lowercase{endgroupdef~}{\mathcharoriginalplusmathcode&}%
edeforiginalminusmathcode{themathcode`-}%
begingrouplccode`~=`- lowercase{endgroupdef~}{\mathcharoriginalminusmathcode&}%
mathcode`+ "8000
mathcode`- "8000
begin{array}[#1]{@{}r@{;}r@{}}
& #2 \
hline
=& thenumexpr#2relax
end{array}%
$%
}

begin{document}

Xquad % 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)







share|improve this answer














share|improve this answer



share|improve this answer








edited 12 hours ago

























answered 12 hours ago









jfbu

44.3k65143




44.3k65143








  • 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
    12 hours ago














  • 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
    12 hours ago








1




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
12 hours ago




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
12 hours ago










up vote
6
down vote













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 an arbitrary number of summands. The preceding code dealt with the case outlined in the original query, which involved exactly two terms in the summation. The following solution, which is still LuaLaTeX-based, works as follows:




  • The LaTeX macro mysum takes one optional argument (the position 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 sets up an array environment, calls the Lua function perform_summation to perform most of the actual work, and terminates the array.



  • The perform_summation 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 sum of the entries and (b) print out each entry on a separate row. Finally, it prints the value of the sum of the entries.



    It is entirely valid, from a syntactic point of view, to execute mysum with just one entry, e.g., mysum{10}.




In the following screenshot, the 3 - symbols at the left-hand and right-hand edged 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}


-- Obtained from https://stackoverflow.com/a/19263313
function string:split( inSplitPattern, outResults )
if not outResults then
outResults = { }
end
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}





share|improve this answer



















  • 1




    thenumexpr#2+#3relax 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
    13 hours ago








  • 1




    (count0=#2relaxadvancecount0by#3relaxthecount0relax)
    – jfbu
    13 hours ago






  • 2




    @jfbu - But where's the fun if I can't use directlua and tex.sprint? :-)
    – Mico
    13 hours ago






  • 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
    12 hours ago








  • 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
    12 hours ago















up vote
6
down vote













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 an arbitrary number of summands. The preceding code dealt with the case outlined in the original query, which involved exactly two terms in the summation. The following solution, which is still LuaLaTeX-based, works as follows:




  • The LaTeX macro mysum takes one optional argument (the position 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 sets up an array environment, calls the Lua function perform_summation to perform most of the actual work, and terminates the array.



  • The perform_summation 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 sum of the entries and (b) print out each entry on a separate row. Finally, it prints the value of the sum of the entries.



    It is entirely valid, from a syntactic point of view, to execute mysum with just one entry, e.g., mysum{10}.




In the following screenshot, the 3 - symbols at the left-hand and right-hand edged 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}


-- Obtained from https://stackoverflow.com/a/19263313
function string:split( inSplitPattern, outResults )
if not outResults then
outResults = { }
end
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}





share|improve this answer



















  • 1




    thenumexpr#2+#3relax 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
    13 hours ago








  • 1




    (count0=#2relaxadvancecount0by#3relaxthecount0relax)
    – jfbu
    13 hours ago






  • 2




    @jfbu - But where's the fun if I can't use directlua and tex.sprint? :-)
    – Mico
    13 hours ago






  • 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
    12 hours ago








  • 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
    12 hours ago













up vote
6
down vote










up vote
6
down vote









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 an arbitrary number of summands. The preceding code dealt with the case outlined in the original query, which involved exactly two terms in the summation. The following solution, which is still LuaLaTeX-based, works as follows:




  • The LaTeX macro mysum takes one optional argument (the position 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 sets up an array environment, calls the Lua function perform_summation to perform most of the actual work, and terminates the array.



  • The perform_summation 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 sum of the entries and (b) print out each entry on a separate row. Finally, it prints the value of the sum of the entries.



    It is entirely valid, from a syntactic point of view, to execute mysum with just one entry, e.g., mysum{10}.




In the following screenshot, the 3 - symbols at the left-hand and right-hand edged 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}


-- Obtained from https://stackoverflow.com/a/19263313
function string:split( inSplitPattern, outResults )
if not outResults then
outResults = { }
end
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}





share|improve this answer














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 an arbitrary number of summands. The preceding code dealt with the case outlined in the original query, which involved exactly two terms in the summation. The following solution, which is still LuaLaTeX-based, works as follows:




  • The LaTeX macro mysum takes one optional argument (the position 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 sets up an array environment, calls the Lua function perform_summation to perform most of the actual work, and terminates the array.



  • The perform_summation 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 sum of the entries and (b) print out each entry on a separate row. Finally, it prints the value of the sum of the entries.



    It is entirely valid, from a syntactic point of view, to execute mysum with just one entry, e.g., mysum{10}.




In the following screenshot, the 3 - symbols at the left-hand and right-hand edged 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}


-- Obtained from https://stackoverflow.com/a/19263313
function string:split( inSplitPattern, outResults )
if not outResults then
outResults = { }
end
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}






share|improve this answer














share|improve this answer



share|improve this answer








edited 5 hours ago

























answered 13 hours ago









Mico

269k30364748




269k30364748








  • 1




    thenumexpr#2+#3relax 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
    13 hours ago








  • 1




    (count0=#2relaxadvancecount0by#3relaxthecount0relax)
    – jfbu
    13 hours ago






  • 2




    @jfbu - But where's the fun if I can't use directlua and tex.sprint? :-)
    – Mico
    13 hours ago






  • 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
    12 hours ago








  • 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
    12 hours ago














  • 1




    thenumexpr#2+#3relax 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
    13 hours ago








  • 1




    (count0=#2relaxadvancecount0by#3relaxthecount0relax)
    – jfbu
    13 hours ago






  • 2




    @jfbu - But where's the fun if I can't use directlua and tex.sprint? :-)
    – Mico
    13 hours ago






  • 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
    12 hours ago








  • 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
    12 hours ago








1




1




thenumexpr#2+#3relax 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
13 hours ago






thenumexpr#2+#3relax 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
13 hours ago






1




1




(count0=#2relaxadvancecount0by#3relaxthecount0relax)
– jfbu
13 hours ago




(count0=#2relaxadvancecount0by#3relaxthecount0relax)
– jfbu
13 hours ago




2




2




@jfbu - But where's the fun if I can't use directlua and tex.sprint? :-)
– Mico
13 hours ago




@jfbu - But where's the fun if I can't use directlua and tex.sprint? :-)
– Mico
13 hours ago




1




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
12 hours ago






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
12 hours ago






1




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
12 hours ago




@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
12 hours ago










up vote
5
down vote













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}

Xquad % 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






share|improve this answer























  • 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
    13 hours ago










  • @Andrew indeed!
    – egreg
    12 hours ago















up vote
5
down vote













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}

Xquad % 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






share|improve this answer























  • 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
    13 hours ago










  • @Andrew indeed!
    – egreg
    12 hours ago













up vote
5
down vote










up vote
5
down vote









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}

Xquad % 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






share|improve this answer














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}

Xquad % 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







share|improve this answer














share|improve this answer



share|improve this answer








edited 10 hours ago

























answered 13 hours ago









egreg

697k8518513117




697k8518513117












  • 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
    13 hours ago










  • @Andrew indeed!
    – egreg
    12 hours ago


















  • 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
    13 hours ago










  • @Andrew indeed!
    – egreg
    12 hours ago
















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
13 hours ago




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
13 hours ago












@Andrew indeed!
– egreg
12 hours ago




@Andrew indeed!
– egreg
12 hours ago










Simeon Simeonov is a new contributor. Be nice, and check out our Code of Conduct.










 

draft saved


draft discarded


















Simeon Simeonov is a new contributor. Be nice, and check out our Code of Conduct.













Simeon Simeonov is a new contributor. Be nice, and check out our Code of Conduct.












Simeon Simeonov is a new contributor. Be nice, and check out our Code of Conduct.















 


draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2ftex.stackexchange.com%2fquestions%2f460078%2fsumming-numbers-like-fractions%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Quarter-circle Tiles

build a pushdown automaton that recognizes the reverse language of a given pushdown automaton?

Mont Emei