When I type '~2.1' here, the distance between ~ and 2.1 is perfect (i.e. exactly what I want). How can it be achieved in LaTeX?
With $\sim\,2.1$, the distance between them is too large.
\sim acts like a relation and therefore is surrounded by a \thickmuskip, similar to what you'll find around =:
$a \sim b$
$a = b$
If you add \showoutput to your document, you'll find the spacing inserted in the .log:
....\mathon <- $
....\OML/cmm/m/it/10 a <- a
....\glue(\thickmuskip) 2.77771 plus 2.77771 <- \thickmuskip
....\OMS/cmsy/m/n/10 ^^X <- \sim
....\penalty 500 <- ...penalty to limit line breaks
....\glue(\thickmuskip) 2.77771 plus 2.77771 <- \thickmuskip
....\OML/cmm/m/it/10 b <- b
....\mathoff <- $
----------------------------------------
....\mathon <- $
....\OML/cmm/m/it/10 a <- a
....\glue(\thickmuskip) 2.77771 plus 2.77771 <- \thickmuskip
....\OT1/cmr/m/n/10 = <- =
....\penalty 500 <- ...penalty to avoid line breaks
....\glue(\thickmuskip) 2.77771 plus 2.77771 <- \thickmuskip
....\OML/cmm/m/it/10 b <- b
....\mathoff <- $
You can change the setting of \sim as a relation to be set as an ordinary math element using {\sim} or \mathord{\sim}, and then add spacing to suit your needs.
\documentclass{article}
\begin{document}
\begin{tabular}{ l l }
\verb|\sim 2.1|: &
$\sim 2.1$ \
\verb|\sim , 2.1|: &
$\sim , 2.1$ \
\verb|{\sim} 2.1|: &
${\sim} 2.1$ \
\verb|\mathord{\sim} 2.1|: &
$\mathord{\sim} 2.1$ \
\verb|{\sim} , 2.1|: &
${\sim} , 2.1$ \
\verb|\mathord{\sim} , 2.1|: &
$\mathord{\sim} , 2.1$
\end{tabular}
\end{document}
\documentclass{article}
\begin{document}
%>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
$\sim\!2.1$
$\sim2.1$
%<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
\end{document}
\,– user187802 Mar 14 '23 at 20:11\,is supposed to give the smallest space in math mode. – apadana Mar 14 '23 at 20:12\,– user187802 Mar 14 '23 at 20:14$\sim2.1$,$\sim\!2.1$and$\sim\,2.1$all produce the same thing here. Not sure why. Maybe that's because 'elsarticle' is being used as document class. – apadana Mar 14 '23 at 20:18$\sim 2.1$... – user187802 Mar 14 '23 at 20:19