[Tex/LaTex] Input numbers from file

input

I have numbers I need to put into my text in latex. The only possibility I know is using \input. So I put every single number in its own file. E.g. the file foo.dat contains 6.062843465325870040e-01 (I checked for trailing white spaces).

The first problem that appears is, that latex apparently puts a space after \input. So My number is \input{foo.dat}. yields

My number is 6.062843465325870040e-01 .

Note the unwanted space before the dot ..


The next problem is, that I obviously want properly formatted numbers. So I use siunits' \num. But \num{\input{foo.dat}} yields an error.

How can I fix this, or are there better solutions (without generating the properly formatted latex code as a file).


I considered https://stackoverflow.com/questions/29078107/insert-values-from-a-file-in-a-latex-document for my solution so far.

Best Answer

\unskip is your friend.

% arara: pdflatex
\RequirePackage{filecontents}
\begin{filecontents*}{foo.dat}
  6.062843465325870040e-01
\end{filecontents*}

\documentclass{article}

\begin{document}
My number is
  \textit{\input{foo.dat}\unskip}.
\end{document}

For usage with siunitx you might want to use the catchfile package:

% arara: pdflatex
\begin{filecontents*}{foo.dat}
  6.062843465325870040e-01
\end{filecontents*}

\documentclass{article}
\usepackage{siunitx}
\usepackage{catchfile}

\begin{document}
My number is
  \CatchFileDef{\foonum}{foo.dat}{}%
  \num\foonum.
\end{document}

output

If you have to do this very often it might be useful to wrap this process into a macro.

% arara: pdflatex
\begin{filecontents*}{foo.dat}
  6.062843465325870040e-01
\end{filecontents*}

\documentclass{article}
\usepackage{siunitx}
\usepackage{catchfile}

\newcommand*\OutputFileNum[2][\num]{%
  \CatchFileDef{\tempnum}{#2}{}%
  #1{\tempnum}%
}

\begin{document}
My number is \OutputFileNum{foo.dat}.
\end{document}
Related Question