The following stores the value of the section
counter minus 1 as a \label
at the end of the document. It's then retrieved using a direct form of \ref
and turned into a string using fmtcount
.

\documentclass{article}
\usepackage{fmtcount,xfp}
\usepackage{lipsum}
\makeatletter
\AtEndDocument{%
\def\@currentlabel{\inteval{\value{section}-1}}%
\label{foolabel}%
}
\newcommand{\foo}{%
\ifcsname r@foolabel\endcsname
\expandafter\numberstringnum\expandafter{\expandafter\@firstoftwo\r@foolabel}%
\else
0%
\fi
}
\makeatother
\begin{document}
\sloppy
\section{Introduction}
There are \foo{} remaining sections.
\section{First section}\lipsum[1-50]
\section{Second section}\lipsum[1-50]
\section{Third section}\lipsum[1-50]
\section{Fourth section}\lipsum[1-50]
\section{Fifth section}\lipsum[1-50]
\end{document}
Since it uses the \label
-\ref
system to extract the last sectional number, you need to compile twice with every change in the number of \section
s (so the \ref
erences can settle).
If you're dealing with unnumbered sections and want to include them as well (typically a reference section), then you can use the following setup:
\documentclass{article}
\usepackage{fmtcount,xfp}
\usepackage{lipsum}
\newcounter{totsection}
\let\oldsection\section
\renewcommand{\section}{\stepcounter{totsection}\oldsection}
\makeatletter
\AtEndDocument{%
\def\@currentlabel{\inteval{\value{totsection}-1}}%
\label{foolabel}%
}
\newcommand{\foo}{%
\ifcsname r@foolabel\endcsname
\expandafter\numberstringnum\expandafter{\expandafter\@firstoftwo\r@foolabel}%
\else
0%
\fi
}
\makeatother
\begin{document}
\sloppy
\section{Introduction}
There are \foo{} remaining sections.
\section{First section}\lipsum[1-50]
\section{Second section}\lipsum[1-50]
\section{Third section}\lipsum[1-50]
\section{Fourth section}\lipsum[1-50]
\section{Fifth section}\lipsum[1-50]
\section*{Sixth section}\lipsum[1-50]
\end{document}
It uses a different counter totsection
that counts a section whether it's numbered or not.
\the\numexpr 6-\thesection\relax
– Steven B. Segletes Dec 1 '20 at 18:56