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.

1
  • 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
    Commented May 9, 2011 at 11:13

2 Answers 2

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
4
  • 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
    Commented May 9, 2011 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
    Commented May 9, 2011 at 12:31
  • oh, I see: that's quite nice!
    – oceanhug
    Commented May 9, 2011 at 13:12
  • 1
    @oceanhug: Also see Leo's answer to this similar question: tex.stackexchange.com/questions/9132/… Commented May 10, 2011 at 8: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}
1
  • you need % not \% at the lua side, so \directlua{tex.print(string.format("\@percentchar0.3f", 10.1234567))} Commented Jul 1, 2015 at 7:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .