[Tex/LaTex] How to print \frac{1}{2} by a single Unicode character

fontspecfractionsmath-modesymbolsunicode-math

I am looking for a command which would print simple fractions like 1/2, 1/3 etc using glyphs available in modern TTF/OTF fonts. Ideally, I want this command to output ordinary \frac{1}{2}, \frac{1}{3} in case if my document is compiled with (PDF)LaTeX, but outputs something like $\text{\char"00BD}$ in case if the compiler is XeLaTeX of LuaLaTeX (and fontspec and / or unicode-math is loaded) and required Unicode character is available in current font.

Is such a command already invented by somebody?

Best Answer

You might try

\documentclass[a4paper]{article}
\usepackage{ifxetex,ifluatex}

\newif\ifunicode
\ifxetex\unicodetrue\else\ifluatex\unicodetrue\fi\fi 

\ifunicode
  \usepackage{unicode-math}
  \setmainfont[Ligatures=TeX,Fractions=On]{XITS}
  \setmathfont{XITS Math}

  \makeatletter
  \let\@@@frac\frac
  \def\frac#1#2{\sbox0{#1/#2}\sbox2{#1\phantom{/}#2}%
    \ifdim\wd0=\wd2 % no corresponding character
      \@@@frac{#1}{#2}%
    \else
      \mbox{#1/#2}%
    \fi}
  \makeatother
\fi

\begin{document}
1/2$\frac{1}{2}\frac{12}{11}$
\end{document}

Here I assume that a vulgar fraction width is different than the width of the slashed form, which seems rather likely to happen.

However I would advise not to use vulgar fractions in a mathematical context.

Related Question