How to use SIrange in math mode

I am not sure why this is not the default behaviour, but if you specify range-phrase = {\text{~to~}} you get the same behavior in and out of math mode:

enter image description here

\documentclass{book}
\usepackage{siunitx} 
\sisetup{mode=text,range-phrase = {\text{~to~}}}
\begin{document}
\SIrange{1}{2}{\watt}\\
$\alpha=\SIrange{1}{2}{\watt}$
\end{document}

Peter has given an answer to make the range phrase print in text mode, which probably solves the case in point. However, there is a reason that siunitx does not do this by default. In particular, in the documentation it states that \SIrange should only be used in text mode.

To see why this is, try the following demonstration.

\documentclass{article}
\usepackage{siunitx}
\begin{document}
Some filler text.
Some filler text.
Some filler text.
Some filler text.
$1\,$m to $10\,$m

Some filler text.
Some filler text.
Some filler text.
Some filler text.
\SIrange{1}{10}{\m}

\sisetup{range-phrase = \text{ to }}
Some filler text.
Some filler text.
Some filler text.
Some filler text.
\SIrange{1}{10}{\m}

\sisetup{range-phrase = \text{ to }\break}
Some filler text.
Some filler text.
Some filler text.
Some filler text.
\SIrange{1}{10}{\m}

\end{document}

What you'll find is that the use of \text here prevents a line break. More importantly, when we force a line break in conjunction with \text, the end of the line is wrong. There is no reliable way of setting up an \ensuretext macro other than inserting an hbox, and so that is what happens with \text. Within such a box, a space which occurs at the end of a line will not be discarded, and so the layout is wrong. Thus while most of the time this looks fine, if the end of the line comes at an inopportune place then disaster will strike. (See for example https://bitbucket.org/josephwright/siunitx/issue/156/unbreakable-space-in-range-phrases where this came up 'in the wild'.) There is no good solution other than stating that \SIrange should be used in text mode, and so this is the official position. Hence the standard settings are such that they work correctly in all supported cases.

Tags:

Siunitx