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.
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.
\ensuremath :-)
– Gonzalo Medina
Jan 20 '14 at 00:43
\frac command...
– Mico
Jan 20 '14 at 05:58
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}
\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 01:34
$\frac{2}{3}$is more real and good IMHO :) – Jan 20 '14 at 00:07\frac{1,000}{2,000}? – Ethan Bolker Jan 20 '14 at 00:55\fr{{1,000},{2,000}}– A.Ellett Jan 20 '14 at 01:38