Count digits of result of arithmetic operation
The usual problem: \eval
is not expandable.
Here's a more straightforward implementation with expl3
.
\documentclass{article}
\usepackage{xparse,xfp}
\ExplSyntaxOn
\NewExpandableDocumentCommand{\CountDigits}{m}
{
\cp_count_digits:e { #1 }
}
\cs_new:Nn \cp_count_digits:n { \tl_count:n { #1 } }
\cs_generate_variant:Nn \cp_count_digits:n { e }
\ExplSyntaxOff
\begin{document}
% the result of the next is 16, as it should
\CountDigits{0123456789ABCDEF}
% the evaluation gives 12321
\inteval{111*111}
% the counting of digits in the result gives 5, as it should
\CountDigits{\inteval{111*111}}
\end{document}
@egreg explained you why your approach fails: your macro is not expandable. There are two options: either you switch gears and use the expl3
machinery. There is nothing wrong with that. On the other hand, if you use pgf
, tikz
and/or pgfplots
anyway, it is arguably preferable to build these functions into the pgf ecosystem. For many functions, this has been done already, in particular digitsum is already available. So you could just use it. I actually advise against using a macro but suggest to use the parsing and number printing machinery, but I added a macro, too.
\documentclass{article}
\usepackage{pgf}
\makeatletter
\newcount\c@Digits
\newcount\c@Powers
\pgfmathdeclarefunction{digitcount}{1}{%
\begingroup%
\global\c@Digits=0%
\expandafter\DigitCount@i#1\@nil%
\pgfmathparse{int(\the\c@Digits)}%
\pgfmathsmuggle\pgfmathresult\endgroup}
\def\DigitCount@i#1#2\@nil{%
\advance\c@Digits by \@ne%
\ifx\relax#2\relax\else\DigitCount@i#2\@nil\fi%
}
\makeatother
\newcommand{\DigitCount}[1]{\pgfmathparse{digitcount(int(#1))}\pgfmathresult}
\begin{document}
If you really want a marco: \DigitCount{111*111}
Cross--check: \pgfmathparse{int(111*111)}\pgfmathprintnumber\pgfmathresult
I'd suggest parsing within the pgf system: \pgfmathparse{digitcount(int(111*111))}\pgfmathprintnumber\pgfmathresult
Works with strings, too: \pgfmathparse{digitcount("0123456789ABCDEF")}\pgfmathprintnumber\pgfmathresult
\end{document}