Take the 2-minute tour ×
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
3  
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
add comment

2 Answers

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
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
1  
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: tex.stackexchange.com/questions/9132/… –  Martin Tapankov May 10 '11 at 8:15
add comment

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}
share|improve this answer
add comment

Your Answer

 
discard

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.