Getting length as number?

You can remove the pt unit from the length using \strip@pt as shown below. I you want the number in cm you would have to convert it by yourself.

\documentclass{article}

\makeatletter
\newcommand*{\getlength}[1]{\strip@pt#1}
% Or rounded back to `cm` (there will be some rounding errors!)
%\newcommand*{\getlength}[1]{\strip@pt\dimexpr0.035146\dimexpr#1\relax\relax}

\makeatother

\begin{document}

Test: \getlength{\textwidth}  % Result: 345

\end{document}

Another alternative which is more flexible and also allows you to store the resulting number in a macro is to use pgfmath (pgf package). It also allows you to easily convert the number to cm:

\documentclass{article}

\usepackage{pgf}
\newcommand*{\getlength}[2]{%
   \pgfmathsetmacro#1{#2}%  Result in `pt`
   % Or:
   %\pgfmathsetmacro#1{0.0351459804*#2}%  Result in `cm`
}

\begin{document}

\getlength{\myNum}{\textwidth}

Test: \myNum % Result: 345.0

\end{document}

There is also the round( ) function for pgfmath which allows you to round the number, e.g. to two fractional digits. The trick is to multiple it with 100 before the rounding and divide it afterwards by 100.

\documentclass{article}

\usepackage{pgf}
\newcommand*{\getlength}[2]{%
   % Convert to `cm` and round to two fractional digits:
   \pgfmathsetmacro#1{round(3.51459804*#2)/100.0}%
}

\begin{document}

\setlength{\textwidth}{2.123cm}
\getlength{\myNum}{\textwidth}

Test: \myNum% Gives 2.12

\setlength{\textwidth}{2cm}
\getlength{\myNum}{\textwidth}

Test: \myNum% Gives 2.0

\end{document}

The fractional part (like .0) can be avoided by using \pgfmathtruncatemacro instead of \pgfmathsetmacro, but I don't think you need that.


An alternative to Martin's approach is to use TeX's \number primitive, which will give you the underlying integer value in sp

\documentclass{article}

\newcommand*\getlength[1]{\number#1}

\begin{document}

Test: \getlength{\textwidth}

\end{document}

(TeX does everything in integers, more or less, so lengths are actually stored in sp, which are tiny length units. Everything else is an integer multiple of a value in sp.)

Tags:

Lengths