4

Unfortunately, in some of our documents we need to print both SI units as well as Imperial units. We have some macros defined as follows:

\documentclass{article}
\usepackage{fp}

\def\GPM#1{#1 gpm\FPmul\temp{#1}{3.785}
\FPround\temp{\temp}{2}(\temp\ lpm) }

\def\GALLONS#1{#1 gallons \FPmul\temp{#1}{3.785}
\FPround\temp{\temp}{2}(\temp\ litres)}

\def\LPM#1{#1 lpm\FPdiv\temp{#1}{3.785}
\FPround\temp{\temp}{2}(\temp\ gpm)}

\begin{document}
\noindent
\GALLONS{200.00}\\
\GPM{500.00}\\
\LPM{1892.50}
\end{document}

enter image description here

How can one modify the macros, so that if you type a number, the conversion macro picks up the number of decimals automatically and sets the conversion accuracy to the same number of decimals, i.e., typing \GALLONS{150.000} should typeset 567.750 litres.

  • 2
    Why are you not using siunitx for the units. I can also be used for the rounding. The number of fractional digits can be counted by an recursive macro which reads each a digit a time and increments an counter. – Martin Scharrer Feb 11 '11 at 18:47
  • @Martin I actually took them out to simplify the example! – Yiannis Lazarides Feb 11 '11 at 18:55
  • You can try xstring package to detect the accuracy. – Leo Liu Feb 11 '11 at 19:05
5

Here is an example for gallons.

enter image description here

\documentclass{article}
\usepackage{fp}

\makeatletter
\newcounter{NoDecim@ls}
\def\getDecim@ls#1{%
  \setcounter{NoDecim@ls}{0}%
  \getDecim@ls@i#1!!\@nil}
\def\getDecim@ls@i#1#2\@nil{%
  \ifx!#1\else\stepcounter{NoDecim@ls}\getDecim@ls@i#2\@nil\fi}

\def\GALLONS#1{\Gallons@i#1..\@nil}
\def\Gallons@i#1.#2.#3\@nil{%
  \FPmul\temp{#1}{3.785} #1%
  \ifx\relax#2\relax\else%
    \FPmul\tempD{#2}{3.785}%
    \FPadd\temp\temp\tempD%
    .#2%
  \fi
  \getDecim@ls{#2}%
  \FPround\temp\temp{\theNoDecim@ls}
  gallons (\temp\ litres)}
\makeatother

\begin{document}

\GALLONS{200.00}\\

\GALLONS{150.000} should typeset 567.750 litres.

\GALLONS{150.00} should typeset 567.75 litres.

\GALLONS{150} should typeset 568 litres.
\end{document}
3
\documentclass{article}
\usepackage{xstring}
\usepackage{fp}
\newcount\acc
\begin{document}

\def\gallons#1{\IfDecimal{#1}%
  {\StrLen{#1}[\templen]%
   \StrPosition{#1}{.}[\temppos]%
   \ifnum\temppos=0%
     \def\theacc{0}%
   \else
     \acc=\numexpr\templen-\temppos
     \edef\theacc{\the\acc}%
   \fi
   \FPupn\result{3.785 #1 * \theacc{} round}%
   \result
  }%
  {NaN} litres}

\gallons{?}      % NaN litres

\gallons{150}    % 568 litres

\gallons{150.0}  % 567.8 litres

\gallons{150.00} % 567.75 litres

\gallons{150.000}% 567.750 litres

\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.