Sign up ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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.

share|improve this question
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 9 '11 at 11:13

2 Answers 2

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:



10. \\
10.1 \\
10.12 \\
10.123 \\
10.1234 \\


It gets:

share|improve this answer
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 9 '11 at 12:09
It does work everywhere, using \num command. You should read the manual carefully before use it, it is quite complex. – Leo Liu May 9 '11 at 12:31
oh, I see: that's quite nice! – oceanhug May 9 '11 at 13:12
@oceanhug: Also see Leo's answer to this similar question:… – Martin Tapankov May 10 '11 at 8:15

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:

    {\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

share|improve this answer
you need % not \% at the lua side, so \directlua{tex.print(string.format("\@percentchar0.3f", 10.1234567))} – David Carlisle Jul 1 at 7:20

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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