1

I'm trying to use the \widthof command (calc package) inside the \ifdimcomp command (etoolbox package), but I keep getting an error "Missing number, treated as zero" which confuses me. I'm trying to test whether a line of text can fit on a single line. If I substitute the \widthof command with a specified unit length, the \ifdimcomp command works, just not the way I want it to.

\documentclass{article}
\usepackage{calc}
\usepackage{etoolbox}
\newcommand{\cmd}[1]{%
    %\ifdimcomp{〈dimen expression〉}{〈relation〉}{〈dimen expression〉}{〈true〉}{〈false〉}; see etoolbox package
    \ifdimcomp{\widthof{#1}}{<}{\textwidth}%
    {TRUE}%
    {FALSE}
}
\newcommand{\cmdtwo}[1]{%
    %\ifdimcomp{〈dimen expression〉}{〈relation〉}{〈dimen expression〉}{〈true〉}{〈false〉}; see etoolbox package
    \ifdimcomp{11pt}{<}{\textwidth}%
    {TRUE}%
    {FALSE}
}
\newcommand{\alphabet}{abcdefghijklmnopqrstuvwxyz}
\begin{document}
\cmd{Hello world}\par%doesnt work
\cmd{\alphabet}\par%doesnt work
\cmd{\alphabet\alphabet\alphabet\alphabet}\par%doesnt work
\cmdtwo{Welcome to the wonderful world of learning latex on the latex stack exchange forums!}\par%works
\cmdtwo{\alphabet\alphabet\alphabet\alphabet}%works
\end{document}
1
  • 1
    You can't do that, \widthof does assignments and can't be used in such a test, assign the width of your text to a length with \setlength first. Commented Sep 12, 2022 at 6:05

1 Answer 1

3

You can figure out why it happens if you try out the simplest example

\documentclass{article}
\usepackage{calc}

\begin{document}

\widthof{test}

\end{document}

The output result is test rather than the width number. Actually, \widthof is not reliable because only works only in specific scenarios.

I would recommend going the other way

\documentclass{article}
\usepackage{calc}
\usepackage{etoolbox}
\newcommand{\cmd}[1]{%
    \sbox0{#1}
    \ifdimcomp{\wd0}{<}{\textwidth}%
    {TRUE}%
    {FALSE}
}
\newcommand{\cmdtwo}[1]{%
    \ifdimcomp{11pt}{<}{\textwidth}%
    {TRUE}%
    {FALSE}
}
\newcommand{\alphabet}{abcdefghijklmnopqrstuvwxyz}
\begin{document}
\cmd{Hello world}\par%works
\cmd{\alphabet}\par%works
\cmd{\alphabet\alphabet\alphabet\alphabet}\par%work
\cmdtwo{Welcome to the wonderful world of learning latex on the latex stack exchange forums!}\par%works
\cmdtwo{\alphabet\alphabet\alphabet\alphabet}%works
\end{document}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .