# Doing maths with distance values in LaTeX source code

I have a sty file with the command

\newcommand{\foo}[1]{\noindent\kern#1}


but I'd actually like to have something like

\newcommand{\foo}[1]{\noindent\kern{#1 *0.5}}


meaning that I'd like to have half of the distance the user puts on command \foo to be passed to \kern. This obviously doesn't work.

Do you have any suggestions on how to do this?

(You may ask "why the hell would you want to do that??". Fair question. I'm using someone else's program which generates tex files and I don't have control over the values that come up on the command \foo. I just know that I'd like to have half of what that program chooses.)

-

## migrated from stackoverflow.comFeb 17 '11 at 20:00

This question came from our site for professional and enthusiast programmers.

This is a question for the experts on tex.stackexchange.com/questions :) –  Matten Feb 17 '11 at 19:59

Use the eTeX primitive \dimexpr to allow a factor like before dimension registers:

\newcommand{\foo}[1]{\noindent\kern .5\dimexpr#1\relax}


Note that \dimexpr swallows the \relax and also allows for some arithmetic inside. See the etex_manual for more details.

-
Great stuff! It works perfectly, thanks! –  Surikator Feb 17 '11 at 20:08
@Martin: Please slow down -- I've got only one vote left for today. :-) –  lockstep Feb 17 '11 at 20:09
+1 for teaching me that \dimexpr can optionally swallow a \relax. Yesterday I tried to use \relax as a delimiter for \numexpr, and I just couldn't understand why the \relax is gone although it's not expandable. –  Hendrik Vogt Feb 18 '11 at 9:32
@Hendrik: Yeah, I think you need two \relax then. I find the \relax swallowing extremely useful. Its friends like \numexpr do the same. –  Martin Scharrer Feb 18 '11 at 9:36
It's funny that the short and simple answers (simple for someone who happens to know that stuff) give you often the most up-votes and badges (just got "Nice Answer" and "Enlightened" for this four lines). –  Martin Scharrer Feb 18 '11 at 16:48

Multiplication of dimensions is built into TeX. So you can do this:

\makeatletter
\newcommand{\foo}[1]{%
\dimen@ #1
\kern 0.5\dimen@%
}
\makeatother
\begin{document}

a\foo{72pt}b

a\kern 72pt b

\end{document}


\dimen@ is a dimension register that is by convention for temporary use. The macro \foo saves #1 in this register and then kerns by half of it.

-
The LaTeX kernel also uses \@tempdima to \@tempdimc as temporary dimension registers. –  Norman Gray Feb 17 '11 at 21:12
and you can create your own with \newdimen\mydimen. –  Martin Scharrer Feb 17 '11 at 21:38
@Norman: Thanks for that; I hadn't known that there were others. –  Matthew Leingang Feb 17 '11 at 23:25

In addition to the low-level support described in other answers, you might find the calc package useful, depending on exactly what it is you want to do.

-