\numberwithin{equation}{subsection} fails for subsections "0"

Update

Since the release of LaTeX from 2018/04/01 the mentioned package chngcntr is now part of the LaTeX kernel -- it's not necessary to load it separately.

Using \numberwithin{equation}{subsection} changes the counter output format and shifts the resetting of the equation counter from section to subsection level (i.e. each time \stepcounter{subsection} is used. However, this means that an orphane equation after a \section, but before \subsection will just use the old counter value, from a previous equation.

This resets the counter of equation number each time a new \section is used, but will not change the \theequation command (being the counter formatting macro)

\makeatletter
\@addtoreset{equation}{section}
\makeatother

As an alternative to this low-level variant, it's possible to use

\usepackage{chngcntr}
\counterwithin{equation}{section}

in the preamble.

However, this will not solve the issue with trailing 0 if the subsection number is 0. This can be attacked with a conditional within \theequation or -- the better way -- avoid equations outside of \subsection if subsection is the driver counter.

\documentclass[12pt]{article}
\usepackage{amsmath}
\makeatletter
\@addtoreset{equation}{section}
\makeatother
\numberwithin{equation}{subsection}

\begin{document}
\section{1}
\begin{equation}
1
\end{equation}
\subsection{1}
\begin{equation}
1
\end{equation}
\subsection{1}
\begin{equation}
1
\end{equation}
\begin{equation}
1
\end{equation}
\section{1}
\begin{equation}
1
\end{equation}
\subsection{1}
\begin{equation}
1
\end{equation}
\section{1}
\begin{equation}
1
\end{equation}
\subsection{1}
\begin{equation}
1
\end{equation}
\end{document}

enter image description here


I do not see the benefit of using such complicated equation numbers. Numbering equations within sections is more than enough IMHO.

Nevertheless, the additional level can be suppressed, if the subsection counter is zero.

Also \numberwithin does not define a transitive closure. Thus the equation number needs to be reset for each \section, too.

\documentclass[12pt]{article}
\usepackage{amsmath}
\numberwithin{equation}{section}% reset equation counter for sections
\numberwithin{equation}{subsection}
% Omit `.0` in equation numbers for non-existent subsections.
\renewcommand*{\theequation}{%
  \ifnum\value{subsection}=0 %
    \thesection
  \else
    \thesubsection
  \fi
  .\arabic{equation}%
}
\begin{document}
\section{1}
\begin{equation}
1
\end{equation}
\subsection{1}
\begin{equation}
1
\end{equation}
\subsection{1}
\begin{equation}
1
\end{equation}
\begin{equation}
1
\end{equation}
\section{1}
\begin{equation}
1
\end{equation}
\subsection{1}
\begin{equation}
1
\end{equation}
\section{1}
\begin{equation}
1
\end{equation}
\subsection{1}
\begin{equation}
1
\end{equation}
\end{document}

Result