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.

Popularity: 2% [?]

Related posts:

  1. C# Decimal: Literals, Conversions and Formatting
  2. Having Pun with C#
  3. In C#, a string is a String
  4. Constructor Chaining
  5. Change Font Size