[Tex/LaTex] Unicode degree symbol ° in math formulas: \textdegree invalid in math mode

degreesmath-modepdftexunicode

I'd like to be able to simply input a degree symbol as ° in my source code. German keyboards have a key for this, and it makes the source so much more readable. I'm using pdflatex from TeXLive 2012, and this minimal reproducing example:

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{textcomp}
\begin{document}
Degree symbol in plain text works: 90° is a right angle.
Degree in math won't work: $\cos(90°) = 0$.
\end{document}

Compiling this document, I get the message

LaTeX Warning: Command \textdegree invalid in math mode on input line 11.

printed twice. Looking at the log for this run, I see an additional error message

Missing character: There is no <B0> in font cmr10!

where <B0> actually refers to a single byte that does not form a valid UTF-8 sequence, so is not properly printable on my console.

I have a rough idea where all of this comes from, but little idea on how to solve this. I'd like to either make the \textdegree symbol work in math mode as well, or have the engine substitute some different command in place of my unicode code point. Ideally, that command would choose the right form depending on whether or not the current mode is math mode, which I don't know how to check (yet). For the final result, it would be nice if the symbol looked the same in both text and math modes, so I'd probably aim for a solution that dies switch to text mode to output that symbol.

But perhaps there is an easier way to do all this. Perhaps there even is a package for this. Searching through previous posts here, I found there is a package unicode-math, but that does not work with pdfLaTeX, and switching the engine does not appear to be a reasonable requirement for most of my applications.

Best Answer

The code below should work:

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{textcomp}
\usepackage{gensymb}
\begin{document}
Degree symbol in plain text works: 90° is a right angle.
Degree in math now work: $\cos(90\degree) = 0$.
\end{document}
Related Question