# How to set a length to the min of two other lengths?

I have declared several lengths in my document: `\bottomMargin` `\topMargin` and `\initialPaperHeight`.

Right now, I am doing this

``````\AtEndDocument{%
\global\paperheight\dimexpr\pagetotal + \bottomMargin + \topMargin \relax
}
``````

But, instead of setting `\paperheight` to `\pagetotal + \bottomMargin + \topMargin`, I would like to set `\paperheight` to the minimum of this value and of `\initialPaperHeight`. In pseudo-code, I would like to do

``````\paperheight = min(\initialPaperHeight, \pagetotal + \bottomMargin + \topMargin)
``````

So, my question is: How should I do?

``````\AtEndDocument{%
\ifdim\dimexpr \pagetotal + \bottomMargin + \topMargin < \initialPaperHeight \relax
\global\paperheight\dimexpr \pagetotal + \bottomMargin + \topMargin
\else
\global\paperheight\initialPaperHeight
\fi
}
``````

However, to me it seems that you are trying to do something complicated here which you shouldn't need.

LaTeX3 has also a function for this:

``````\usepackage{expl3}

\ExplSyntaxOn

\global \paperheight = \dim_min:nn { \initialPaperHeight } { \pagetotal + \bottomMargin + \topMargin }

\ExplSyntaxOff
``````

(untest because you gave no MWE …)

• you should then switch to full expl3 and use something like `\dim_gset` – yo' Dec 21 '15 at 13:11
• @yo' I know … :-) – Tobi Dec 21 '15 at 17:45

I know this is an old question, but I found another solution here, which is LaTeX flavoured rather than TeX flavoured.

Import the `ifthen` package, then

``````% Return in #3 the minimum of the two lengths #1 and #2
\newcommand{\MinLength}[3]{%
\ifthenelse{\lengthtest{\the#1<\the#2}}
{\setlength{#3}{#1}}
{\setlength{#3}{#2}}}

% Return in #3 the maximum of the two lengths #1 and #2
\newcommand{\MaxLength}[3]{%
\ifthenelse{\lengthtest{\the#1>\the#2}}
{\setlength{#3}{#1}}
{\setlength{#3}{#2}}}
``````

`\MinLength` and `\MaxLength` take three lengths as arguments and will set their third argument to the minimum or maximum of their first two. There's a full example at the link above.