rral
rral

Reputation: 584

Number color according to its value in LaTeX

I need to create a table with numeric content, and based on its value, I require it to automatically take a color. For example. if X take the following values:

x < 0; then x will be red
0 <= x < 0.5; then x will be green
0.5 <= x <= 1; then x will be blue

ie: if I create a table with the following

\documentclass{article}
\begin{document}
\begin{table}[]
\begin{tabular}{ccc}
\hline\\
\textbf{a} & \textbf{b} & \textbf{c} \\
\hline\\
-1   & 0   & 1    \\
0.3  & 0.5 & -1   \\
-0.2 & 0.7   & -0.5 \\
\hline\\
\end{tabular}
\end{table}
\end{document}

then the output should be:

enter image description here

but automatically, I know that it can be done by programming with tex but I do not know where to start. Please, any suggestion is welcome

Upvotes: 2

Views: 2682

Answers (1)

Werner
Werner

Reputation: 15095

You can pass each table cell entry through a macro (using collcell) and condition based on the value (using xfp):

enter image description here

\documentclass{article}

\usepackage{collcell,xcolor,xfp}

\newcommand{\fmtnum}[1]{%
  \ifnum\fpeval{#1 < 0} = 1
    \textcolor{red}{$#1$}%
  \else
    \ifnum\fpeval{#1 < 0.5} = 1
      \textcolor{green}{$#1$}%
    \else
      \textcolor{blue}{$#1$}%
    \fi
  \fi
}

\begin{document}

\begin{tabular}{ *{3}{>{\collectcell\fmtnum}c<{\endcollectcell}} }
  \hline
  \multicolumn{1}{c}{\bfseries a} & \multicolumn{1}{c}{\bfseries b} & \multicolumn{1}{c}{\bfseries c} \\
  \hline
  -1   & 0   &  1   \\
   0.3 & 0.5 & -1   \\
  -0.2 & 0.7 & -0.5 \\
  \hline
\end{tabular}

\end{document}

Setting the headings in \multicolumns avoids them being processed by \fmtnum as well.

Upvotes: 2

Related Questions