It’s easy to programmatically set the number of decimal places in a decimal, float or double that is converted to a string. Use the ToString method with the “N” argument summed with the number of decimal places:
float value = 3.1415926F;
int decimalPlaces = 3;
string text = value.ToString( "N" + decimalPlaces );
Note that ‘decimalPlaces’ must be greater than or equal to zero, otherwise an exception will be thrown.
My C# program threw an exception from the following method:
SizeF size = Graphics.MeasureString( text, font );
Unfortunately, the exception’s message was rather obscure: “Parameter is invalid.”
After an investigation, I discovered the error occurred because the font had been previously disposed.
Unfortunately, the Font class does not have the typical IsDisposed property, so there was no way to directly query the font’s disposed state. But I searched in my code and found where I was calling the font’s Dispose method, and then incorrectly trying to use the font again in my call to the MeasureString method.