Below are the rules if you believe it's random. A utility function can be created on the basis of these rules.
If the value contains a comma, newline or double quote, then the String value should be returned enclosed in double quotes.
Any double quote characters in the value should be escaped with another double quote.
If the value does not contain a comma, newline or double quote, then the String value should be returned unchanged.