12

Is there a way to use printf-style number formatting strings in Latex like %.3f, %d, etc? I'm loading some data from csv files using the datatool package and would like to have it displayed exactly to my specifications.

Martin Scharrer
  • 262,582
oceanhug
  • 221
  • 4
    Using % would be pretty awkward for the formatting directive in TeX, so you're not likely to see it done exactly that way – Joseph Wright May 09 '11 at 11:13

2 Answers2

13

I've no idea about datatool. siunitx provides some functions to round numbers. See manual of siunitx: 5.4 Parsing numbers, 5.5 Post-processing numbers

For example:

\documentclass{article}
\usepackage{siunitx}

\begin{document}

\begin{tabular}{S[round-mode=places,round-precision=2]}
10. \\
10.1 \\
10.12 \\
10.123 \\
10.1234 \\
\end{tabular}

\end{document}

It gets:

10.00
10.10
10.12
10.12
10.12
David Carlisle
  • 757,742
Leo Liu
  • 77,365
  • That's not bad, but I actually need something that works anywhere in the text, not only inside tables, i.e. I'd like to do \printf{"%.3f"}{0.3242342} and get the output 0.324. – oceanhug May 09 '11 at 12:09
  • 2
    It does work everywhere, using \num command. You should read the manual carefully before use it, it is quite complex. – Leo Liu May 09 '11 at 12:31
  • oh, I see: that's quite nice! – oceanhug May 09 '11 at 13:12
  • 1
    @oceanhug: Also see Leo's answer to this similar question: http://tex.stackexchange.com/questions/9132/rounding-numbers-in-a-table-truncating-text-in-table – Martin Tapankov May 10 '11 at 08:15
9

If you are willing to use LuaTeX

\directlua{tex.print(string.format("\string\%0.3f", 10.1234567))}

string.format accepts all the usual printf style arguments. The \string\% is needed because % has a special meaning in TeX.

ConTeXt provides a few helper functions so that the above can be written as

\ctxlua{context("\%0.3f", 10.12345)}

If you want, you can easily wrap the above in a macro:

\def\truncate#1#2%
    {\directlua{tex.print(string.format("\string\%0.#1f", #2))}}

or in ConText as

\def\truncate#1#2{\ctxlua{context("\%0.#1f", #2)}}

and then use

\truncate{3}{10.123456}
Aditya
  • 62,301