[Tex/LaTex] Formatting numbers while printing

calculationsformatting

Is there a way to format number strings while printing?

Suppose I have the following declaration:

\newcommand{\MyNumberA}{40}
\newcommand{\MyNumberB}{60}

The following in the text:

\the\numexpr(\MyNumberA*\MyNumberB)\relax

will produce 2400. I want to print 2,400 or 2,400.00.

Am I asking too much or this can be done? How?

Best Answer

You can use siunitx package to do this:

\documentclass{article}
\usepackage[group-separator={,},group-minimum-digits=4]{siunitx}
\begin{document}

\newcommand{\MyNumberA}{40}
\newcommand{\MyNumberB}{60}

\num{\the\numexpr(\MyNumberA*\MyNumberB)\relax}

\end{document}

which produces:

enter image description here

You can define your own command to handle this too:

\documentclass{article}
\usepackage{siunitx}
\newcommand\mynum[1]{\num[group-separator={,},group-minimum-digits=4]{\the\numexpr(#1)\relax}}
\begin{document}

\newcommand{\MyNumberA}{40}
\newcommand{\MyNumberB}{60}

\mynum{\MyNumberA*\MyNumberB}

\end{document}

Regarding comment about non-integer values:

I would follow @egreg's suggestion and take advantage of the fact that siunitx ueses expl3 internally. In this following example, I create a separate command to handle floating point values. I also provided the macro with two arguments. The first argument is optional to allow you to modify how siunitx handles its content:

\documentclass{article}
\usepackage{siunitx}
\ExplSyntaxOn
\DeclareExpandableDocumentCommand\myeval{m}{\fp_eval:n{#1}}
\ExplSyntaxOff
\newcommand\mynum[1]{\num[group-separator={,},group-minimum-digits=4]{\the\numexpr(#1)\relax}}
\newcommand\myfpnum[2][]{\num[group-separator={,},
                            group-minimum-digits=4,
                            round-integer-to-decimal,
                            round-mode=places,#1]{\myeval{#2}}}
\begin{document}

\def\MyNumberA{40}
\def\MyNumberB{60}

\mynum{\MyNumberA*\MyNumberB}

\def\MyNumberA{40.1349}
\def\MyNumberB{60.9982}

\myfpnum[round-precision=3]{\MyNumberA*\MyNumberB}

\end{document}

enter image description here

Related Question