As mentioned elsewhere the DMG tablulates this in the "Making a Monster" section, but there is a precise formula you can use
The precise mathematical formula for this is:
$$ 2 + sgn(\text{CR}-1)*\left\lfloor\frac{|\text{CR}-1|}{4}\right\rfloor $$
where:
$$ sgn(x) = \begin{cases} -1, & \text{if $x\lt 0$} \\ 0, & \text{if $x= 0$} \\
1, & \text{if $x\gt 0$} \\ \end{cases}$$
is the sign (or signum) function.
$$ |x| = x*sgn(x)$$
is the absolute value of x.
$$ \left\lfloor x \right\rfloor = max(m \in \mathbb{Z}| m \le x)$$
is the floor of x. The precise definition of this formula, in words, is "the maximum integer, m, that is less than or equal to x".
This formula works for all CRs in the game (it also works for calculating a character's proficiency bonus if you substitute total character level for CR in the formula).
Taking your example of a CR 2 creature and working through it we get:
$$ 2 + sgn(3-1)*\left\lfloor\frac{|3-1|}{4}\right\rfloor $$
$$ = 2 + sgn(2)*\left\lfloor\frac{|2|}{4}\right\rfloor $$
$$ = 2 + (+1)*\left\lfloor \frac{2}{4} \right\rfloor $$
$$ = 2 + (+1)*0 $$
$$ = 2 $$
If instead we look at a \$\text{CR} = \frac{1}{8}\$ creature we get:
$$ 2 + sgn(\frac{1}{8}-1)*\left\lfloor\frac{|\frac{1}{8}-1|}{4}\right\rfloor $$
$$ = 2 + sgn(-\frac{7}{8})*\left\lfloor\frac{|\frac{-7}{8}|}{4}\right\rfloor $$
$$ = 2 + sgn(-\frac{7}{8})*\left\lfloor\frac{\frac{7}{8}}{4}\right\rfloor $$
$$ = 2 + (-1)*\left\lfloor\frac{7}{8} * \frac{1}{4}\right\rfloor $$
$$ = 2 + (-1)*\left\lfloor \frac{7}{32} \right\rfloor $$
$$ = 2 + (-1)*0 $$
$$ = 2 $$