[Tex/LaTex] How to convert pt/in/cm/mm to em/ex as they are defined at a given point in the document

unit-of-measure

I am using various macros that I have fine-tuned with units like pt and cm. I use those macros normally in certain places (say, in main body text or in footnote text). To properly generalize those macros, I would like to replace the absolute units by relative ones.

Say I have a macro \newcommand*{\aalso}{\textsl{and also}\hspace{1.1pt}}. Say I normally use that macro in footnotes. But now I realize that I made a mistake and would like to change the length 1.1pt to something of the form ...em so that I can use the macro elsewhere. How do I get the right number? I assume that the right way is to define some macro like \emConverter{1.1pt} that, if issued in a footnote context, gives me the length of 1.1pt in a footnote context converted to a relative length in em. It doesn't need to be a LaTeX-parsable value; it's okay if this is just printed out directly into the document, for me to then manually write the new em-value into the source code.

Some relevant questions:

Best Answer

\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\convertto}{mm}
    % #1 = em or ex (or any other unit)
    % #2 = dimen to convert
 {
  \texttt{#2~=~\fp_to_decimal:n { (#2)/(1#1) }#1}
 }
\ExplSyntaxOff

\begin{document}
\convertto{em}{1.1pt}

\convertto{ex}{1.1pt}

\Large
\convertto{em}{1.1pt}

\convertto{ex}{1.1pt}

\end{document}

enter image description here

A variant for also showing a given length (explicit or implicit) in a different unit of measure (default mm); I also added rounding to five digits

\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\convertto}{mm}
    % #1 = em or ex (or any other unit)
    % #2 = dimen to convert
 {
  \texttt{#2~=~\fp_to_decimal:n { round ( (#2)/(1#1), 5 ) }#1}
 }
\DeclareExpandableDocumentCommand{\thelength}{ O{mm} m }
 {
  \fp_to_decimal:n { round ( #2/1#1, 5 ) } #1
 }
\ExplSyntaxOff

\begin{document}
\convertto{em}{1.1pt}

\convertto{ex}{1.1pt}

\Large
\convertto{em}{1.1pt}

\convertto{ex}{1.1pt}

\thelength{\textwidth}

\thelength[cm]{\textwidth}

\end{document}

enter image description here

An example application; we want to modify the output of layout so that it uses millimeters. We need only \thelength:

\documentclass{article}
\usepackage{xparse}
\usepackage{layout}


\ExplSyntaxOn
\DeclareExpandableDocumentCommand{\thelength}{ O{mm} m }
 {
  \fp_to_decimal:n { round ( (#2)/(1#1), 5 ) } #1
 }
\ExplSyntaxOff

% redefine the output macro
\makeatletter
\renewcommand*{\lay@value}[2]{\thelength{\csname #2\endcsname}}
\makeatother

\begin{document}
\layout
\end{document}

I only show the relevant part of the output, with the lengths

enter image description here

Related Question