# New command in TeX for fraction

Now I need to redefine the fractions as follows

By writing \fr{2,3}, we get $\frac{2}{3}$. How can I achieve this? I have tried

\newcommand{\fr}[1,2]{\frac{#1}{#2}}


but got wrong.

-
$\frac{2}{3}$ is more real and good IMHO :) – Harish Kumar Jan 20 '14 at 0:07
What if you wanted to write \frac{1,000}{2,000} ? – Ethan Bolker Jan 20 '14 at 0:55
@EthanBolker \fr{{1,000},{2,000}} – A.Ellett Jan 20 '14 at 1:38
I would also recommend against this, this would not be particularly readable for others. – daleif Jan 20 '14 at 7:52

The following example defines \fr with one argument and separates the numerator and denominator via the help macro \fr@aux:

\documentclass{article}

\makeatletter
\newcommand*{\fr}[1]{%
\fr@aux#1,,\@nil
}
\def\fr@aux#1,#2,#3\@nil{%
\ensuremath{\frac{#1}{#2}}%
}
\makeatother

\begin{document}
$\fr{2,3} = \fr{20,30}$
\end{document}


A variant with error checking:

\documentclass{article}

\makeatletter
\newcommand*{\fr}[1]{%
\fr@aux#1,,\@nil
}
\def\fr@aux#1,#2,#3\@nil{%
\def\fr@param{#2#3}%
\ifx\fr@param\@empty
\errmessage{\string\fr: Missing comma}%
\else
\def\fr@param{#3}%
\ifx\fr@param\fr@check
\else
\errmessage{\string\fr: Too many commas}%
\fi
\fi
\ensuremath{\frac{#1}{#2}}%
}
\def\fr@check{,}
\makeatother

\begin{document}
$\fr{2,3} = \fr{20,30}$

% Trigger errors:
\fr{1}
\fr{2,3,4}
\end{document}

-
Why do you need two commas in \fr@aux#1,,\@nil? I would naïvely think that #1 corresponded to #1,#2 in the defn. of \fr@aux and ,\@nil corresponded to ,#3\@nil. How should I be reading it? – cfr Jan 20 '14 at 1:34
@cfr The second comma is there in case the user forgets to put in the first comma. Then if you wanted you could check for an empty argument and create a more meaningful error message than the one that would result without a second comma. – A.Ellett Jan 20 '14 at 1:36

It's quite easy with xparse:

\documentclass{article}
\usepackage{xparse}
\NewDocumentCommand{\fr}{>{\SplitArgument{1}{,}}m}{\efrac#1}
\NewDocumentCommand{\efrac}{mm}{\ensuremath{\frac{#1}{#2}}}

\begin{document}
Here's \fr{2,3} and also in math $\fr{4,2}=2$.
\end{document}


The argument declared with \SplitArgument is expected to have one comma in it. The macro splits the argument into two braced components, that are passed as argument to \efrac which, in turn, has two arguments.

There's no convenience in being able to type \fr{2,3} instead of the clearer $\frac{2}{3}$, though. Trust me.

-
This must be one of the few times I see you using \ensuremath :-) – Gonzalo Medina Jan 20 '14 at 0:43
I suspect the OP has a keyboard where the curly braces are less easily accessible than is the comma. That, or saving three keystrokes relative to a regular \frac command... – Mico Jan 20 '14 at 5:58