[Tex/LaTex] Extract Section number from Equation reference

cross-referencinghyperref

How can I obtain the number of the Section in which an Equation (or Figure) appears? For instance, I have the reference 3.2, which refers to the second (2nd) Equation in Section 3. How can I extract the 3 (or the 2), such that it is still clickable (using hyperref)?

Preferably it should return "2nd" when it is the second Equation, "3d" when it's the third one, and so on.

MWE:

\documentclass[10pt,a4paper,fleqn]{article}
\usepackage{amsmath}
\usepackage{lipsum}
\usepackage{hyperref}
\hypersetup{colorlinks}
\numberwithin{equation}{section}
\setlength{\parindent}{0pt}
\begin{document}

\section{Start}
\lipsum[1]

\section{Halfway}

The equation \eqref{ThisOne} is the (1st, 2nd, 3d, ...?) Equation in Section (1, 2, 3, ...?).

\section{End}

A famous formula:

\begin{equation}
x_1, x_2 = \frac{ -b \pm \sqrt{b^2 - 4ac} }{ 2a }
\end{equation}

And another one:

\begin{equation}
\sin^2(\varphi) + \cos^2(\varphi) = 1
\label{ThisOne}
\end{equation}

\end{document}

Best Answer

You can do this easily with the help of the refcount (to turn the reference number into a string), xstring (to extract the number before and after the dot), and engord (to get the desired format as ordinal number) packages.

In the following example, I defined the commands \SecNum and \EqNum; the first one gives the section number of the reference and the second one gives the equation number in ordinal notation and turns it into a hyperlink to the given equation:

\documentclass[10pt,a4paper,fleqn]{article}
\usepackage{amsmath}
\usepackage{refcount}
\usepackage{xstring}
\usepackage{engord}
\usepackage{xspace}
\usepackage{lipsum}
\usepackage{hyperref}

\hypersetup{colorlinks}
\numberwithin{equation}{section}
\setlength{\parindent}{0pt}

\newcommand\equ{}
\newcommand\EqNum[1]{%
  \StrBehind{\getrefnumber{#1}}{.}[\equ]%
  \hyperref[#1]{\engordnumber{\equ}\xspace}%
}
\newcommand\SecNum[1]{%
  \StrBefore{\getrefnumber{#1}}{.}\xspace%
}

\begin{document}

\section{Start}
\lipsum[1]

\section{Halfway}

The equation \eqref{ThisOne} is the \EqNum{ThisOne}~Equation in Section \SecNum{ThisOne}.

\section{End}

A famous formula:

\begin{equation}
x_1, x_2 = \frac{ -b \pm \sqrt{b^2 - 4ac} }{ 2a }
\end{equation}

And another one:

\begin{equation}
\sin^2(\varphi) + \cos^2(\varphi) = 1
\label{ThisOne}
\end{equation}

\end{document}

enter image description here

I added \xspace from the xspace package to take care of proper spacing.