Override the spacing on the right of an in-line equation when followed by a punctuation mark

I set \mathsurround to 2pt in order to have a bit more horizontal spacing between text and in-line equations. Is there a way to set it to 0pt on the right whenever the in-line equation is followed by a punctuation mark?

For instance, the code

Let $x=0$ and $y=1$.


is typeset as in the first line below, while I would like it to be as in the second.

Is there a way to achieve this without having to provide every time \hspace{-2pt}?

Edit:

I have already considered @barbarabeeton's advice, that is, to include the punctuation before the final $, but some marks are typeset differently in text mode and math mode. Probably punctuation marks is a bit too restrictive, as I would like to include brackets () [] {} or even the apostrophe '. In addition I would like my code to be flexible, so whenever I decide to change something I don't have to edit the whole document. • although it really isn't a "best practice", you could include the punctuation before the final $ sign. – barbara beeton Apr 29 '14 at 14:17
• Can you explain the reason why you want such a typographic style? I would say that the default version seems more reasonable in the first line. – strpeter Apr 29 '14 at 14:39
• @barbarabeeton Thanks for the hint, I added some details to my question. Besides, I was looking for something closer to a "best practice"... – AndreasT Apr 29 '14 at 14:47
• I try not to have inline equations followed by punctuation, it just looks bad, and in the worst case could change the meaning of $n$! Reword, make into a display. – vonbrand Apr 29 '14 at 20:12

There are two ways. The first is to remove the math surround kern (with a macro before the punctuation); the second is to have punctuation inside the formula, but with a macro that takes care of the space factor and removes the kern.

In the example I show both methods. The third line is with zero mathsurround, with the kerns added manually in order to show the output is the same.

\documentclass{article}

\newcommand{\unms}{\kern-\mathsurround}

\newcommand{\fp}[1]{%
\mbox{#1}%
\xdef\fpuncsf{%
\kern-\mathsurround
\spacefactor\the\sfcode#1\relax
}%
\aftergroup\fpuncsf
}

\setlength{\mathsurround}{2pt}

\begin{document}

Let $x=0$ and $y=1$\unms. There was a sentence ending period.

Let $x=0$ and $y=1\fp.$ There was a sentence ending period.

%% check
\mathsurround=0pt\def\?{\kern2pt }

Let \?$x=0$\? and \?$y=1$. There was a sentence ending period.

\end{document}