I am trying to convert \textwidth to other units I want and do calculations with the number (without the unit).
How does one do this?
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It only takes a minute to sign up.
Sign up to join this communityI am trying to convert \textwidth to other units I want and do calculations with the number (without the unit).
How does one do this?
\strip@pt
removes the unit pt
and eTeX's \dimexpr
can be used for the calculation:
\documentclass{article}
\usepackage{siunitx}
\makeatletter
% #1: macro, which gets the result of the conversion without unit
% #2: length expression
\newcommand*{\converttomm}[2]{%
\edef#1{%
\strip@pt\dimexpr(#2)*2540/7227\relax % 72.27 pt = 1 in = 25.4 mm
}%
}
\makeatother
\begin{document}
\converttomm{\mmTextWidth}{\textwidth}
The text width is \SI{\mmTextWidth}{\milli\meter}.
\end{document}
You can use my calculator
package.
The \LENGTHDIVIDE
command divides two lengths and stores result as a number in a new command, as you need.
Try this code:
\documentclass[a4paper]{article}
\usepackage{calculator}
\begin{document}
\LENGTHDIVIDE{\textwidth}{1mm}{\size}
\size
\end{document}
In a standard a4 article \size
returns 121.25427
Length conversion to decimal using LaTeX3:
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
%\cs_new_eq:NN \calc \fp_eval:n
\cs_new_eq:NN \convertlen \dim_to_decimal_in_unit:nn
\ExplSyntaxOff
\begin{document}
\verb|\textwidth| in \verb|pt|s: \the\textwidth
\makeatletter
\verb|1mm| in \verb|pt|s: \setlength{\@tempdima}{1mm}\the\@tempdima
\makeatother
$\frac{\texttt{\string\textwidth}}{\texttt{1mm}} = \convertlen{\textwidth}{1mm}$
\end{document}
The above defines the user interface \convertlen{<fromlen>}{<tounit>}
using LaTeX3's \dim_to_decimal_in_unit
.
1mm
first approximated by 186467sp
which is what \number\dimexpr 1mm\relax
returns (I obtain same result as you if I do \xinttheiexpr [5]\textwidth/\dimexpr 1mm\relax\relax
.) The computation as in Heiko's answer is more accurate: that would be \xinttheiexpr [5] \textwidth*2540/(7227*65536)\relax
, where the ratio is also in smallest terms635/118407168
.
– user4686
Sep 11 '16 at 19:45
345pt
, the exact value in mm
is 345*2540/7227=292100/2409=121.253632212536322125363221253632...
– user4686
Sep 11 '16 at 19:50
1mm
in sp
is 186467.9811...
, but TeX replaces it by 186467
as it truncates when one assigns dimensions to register. That means basically a relative error of order 0.5*10^-5
. And indeed the \dim_to_decimal_in_unit
provides here a result which is wrong at the sixth decimal.
– user4686
Sep 11 '16 at 19:59