Rounding numbers in a table / Truncating text in table

For numbers:

There are some packages, like siunitx and math engine of tikz (especially in pgfplotstable), which can used to format numbers in LaTeX. numprint may be the simplest one, and can be easily used in tabulars.

numprint package privides n and N column types for numbers in tabular, and \nprounddigits for set the precision. An example:

% \usepackage{numprint} in preamble
\npdecimalsign{.}
\nprounddigits{2}
\begin{tabular}{c|n{5}{2}|}
foo & 12345 \\
bar & 12345.12345 \\
baz & 0.00012345 \\
\end{tabular}
\npnoround

Please read the manual for more options.


For common characters, @TH has showed some TeX trick. However, you can use xstring package or something else to do the dirty work. I don't know how to get full control in tabular, so here is just a incomplete solution, a mix of xtring and primitive TeX:

\halign{\StrLeft{#}{4} \cr
 abc \cr
 abcde \cr
 abcdefg \cr
}

Any further suggestions are welcome.


Here's one way to do it that's a bit of a hack (which is to say that Leo Liu's answer is far better, it's just fun to try to do this yourself sometimes):

\documentclass{article}
\usepackage{array}
\usepackage{fp}
\newcolumntype{T}{>{\trunc}r}
\def\trunc\ignorespaces#1\\{%
        \FPset\a{#1}
        \FPround\a\a4
        \a
        \\
}
\begin{document}
\begin{tabular}{>{$}l<{$}T}
\pi  & 3.14159265358979323848\\
e    & 2.71828182845904523536\\
\phi & 1.61803399\\
x    & 37\\
\end{tabular}
\end{document}

alt text

The T specifier has to be at the end of the row and it must be terminated with a \\. You could write an analogous one that works in the middle of the row by delimiting it with & rather than \\.

The original version differed only in the definition of \trunc.

\def\trunc#1.#2#3#4#5#6\\{#1.#2#3#4#5\\}

\documentclass{article}
\usepackage{array,xstring}

\newcolumntype{N}{>{\GobbleA} r<{;;} }
\def\GobbleA\ignorespaces#1.#2;;{%
  \ignorespaces#1.\StrLeft{#2}{4}}

\newcolumntype{S}{>{\GobbleB} l }
\def\GobbleB#1#2\\{\StrLeft{#2}{4}\\}

\begin{document}
\begin{tabular}{>{$}l<{$} N S}
\pi  & 3.14159265358979323848 & delicious \\
e    & 2.71828182845904523536 & foo \\
\phi & 1.61803399             & extraordinarylong \\
x    & 37.11111               & { } \\
\end{tabular}

\end{document}

alt text