I'm currently working on making a kind of textbook for Japanese math learners. Then, I made a counter macro as below.
It seems to work nice in normal environment, as far as I know. But once I put it into align environment, it will no longer work correctly. I think it is double counted; for instance, when I use \utoi three times, it will start from the fourth letter.
I would appreciate it very much if anyone could fix it. Thanks in advance.
\documentclass[fleqn, uplatex]{jsarticle}
\usepackage{amsmath}
\global\newcount\kAnAc
\def\Cleariroha{\kAnAc=0}
\Cleariroha
\makeatletter
\def\iroha{\@ifnextchar [{\K@N@@}{\K@N@}}
\def\K@N@{%
\global\advance\kAnAc\@ne%
\ifcase\kAnAc ×\or イ\or ロ\or ハ\or ニ\or ホ\or ヘ\or ト\or チ\or リ\or ヌ\or ル\or ヲ\or ワ\or カ\or ヨ\or タ\or レ\or ソ\or ツ\or ネ\or ナ\or ラ\or ム\or ×\fi%
}
\def\K@N@@[#1]{%
\batchmode%
\ifcase\ref{#1} ×\or イ\or ロ\or ハ\or ニ\or ホ\or ヘ\or ト\or チ\or リ\or ヌ\or ル\or ヲ\or ワ\or カ\or ヨ\or タ\or レ\or ソ\or ツ\or ネ\or ナ\or ラ\or ム\or ×\fi%
\errorstopmode}%
\def\Klabel#1{\@bsphack
\protected@write\@auxout{}%
{\string\newlabel{#1}{{\the\kAnAc}{\thepage}}}%
\@esphack}
\makeatother
\newcommand{\utoi}[1]{\underset{\iroha}{\underline{#1}}}
\begin{document}
$\utoi{3}$, $\utoi{5}$
\Cleariroha
\begin{align*}
y&=\utoi{a}x+\utoi{b}\\
&=\utoi{5}x+\utoi{4}
\end{align*}
\end{document}
Just in case: In order to run Japanese language in TeX file, you need to make the following file as "latexmkrc"
$latex = 'uplatex';
$bibtex = 'upbibtex';
$dvipdf = 'dvipdfmx %O -o %D %S';
$makeindex = 'mendex -U %O -o %D %S';
$pdf_mode = 3;

\the\kAnAc? Anyway the problem is due to the fact thataligntypesets its argument twice, hence the double counting. A possible workaround usingamsmath's internal macro\@ifmeasuring@is shown in this answer. – campa Sep 22 '20 at 07:27