# Conditional Latex table: Cell value color based on its value

I would like to create a conditional where values less than 7 are in red and values greater than or equal to 7 are in blue.

I would like a result like the one below:

Follows my MWE.

\documentclass[12pt,a4paper]{article}
\usepackage[brazil]{babel}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[pdftex]{color}
\usepackage{longtable}

\begin{document}

\pagestyle{empty}

\centering
\begin{spreadtab}{{longtable}{c c c c c c}}
\hline
@ {\bf Number} & @ {\bf 1º Exam} & @ {\bf 2º Exam} & @ {\bf Mean} & @ {\bf Final} & @ {\bf Situation} \\
\hline
\rowcolor{gray!25}
@ 18101610 & 7 & 8.5 & (b2+c2)/2 & - & \\
@ 18103839 & 6 & 4.3 & (b3+c3)/2 & 7 & \\
\rowcolor{gray!25}
@ 18101547 & 5.4 & 3.5 & (b4+c4)/2 & 6 & \\
@ 18100204 & 7 & 8 & (b5+c5)/2 & - & \\
\rowcolor{gray!25}
@ 14101294 & 9 & 10 & (b6+c6)/2 & - & \\
@ 18101505 & 3.7 & 1.5 & (b7+c7)/2 & - & \\
\hline

\end{document}


Other questions have already addressed this issue, but in my case the \usepackage[table]{xcolor} is conflicting with \usepackage{collcell,xfp}. The conditional is changing the color of all the cells, even the text is getting colored.

\documentclass[12pt,a4paper]{article}
\usepackage[brazil]{babel}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[pdftex]{color}
\usepackage{collcell, xfp}
\usepackage{longtable}

\begin{document}

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

\centering
\begin{tabular}{ *{6}{>{\collectcell\fmtnum}c<{\endcollectcell}}}
\hline
{\bf Number} & {\bf 1º Exam} & {\bf 2º Exam} & {\bf Mean} & {\bf Final} & {\bf Situation} \\
\hline
\rowcolor{gray!25}
18101610 & 1 & 2 & 1.5 &  & \\
18103839 & 4 & 7.5 & 5.75 & 7 & \\
\rowcolor{gray!25}
18101547 & 5.4 & 3.5 & 4.45 & 6 & \\
18100204 & 7 & 8 & 7.5 & - & \\
\rowcolor{gray!25}
14101294 & 9 & 10 & 9.5 & - & \\
18101505 & 3.7 & 1.5 & 2.6 & - & \\
\hline
\end{tabular}
\end{document}


Similar questions:

https://stackoverflow.com/questions/52123278/number-color-according-to-its-value-in-latex

https://tex.stackexchange.com/a/174360/187808

Automatic coloring of numbers according to size

• – user187808 Apr 30 at 14:09
• – user187808 Apr 30 at 14:10
• Off-topic: Nowadays it's best not to force a driver to a package (the pdftex option to \usepackage{color}) unless you really know what you're doing. The package code usually is clever enough to sort out the driver code correctly by itself. – Phelype Oleinik Apr 30 at 14:14