title: How do I format a Decimal to a programatically controlled number of decimals in c#?
body: <p>How can I format a number to a fixed number of decimal places (keep trailing zeroes) where the number of places is specified by a variable?</p>
  
  <p>e.g. </p>
  
  <pre><code>int x = 3;
  Console.WriteLine(Math.Round(1.2345M, x)); // 1.234 (good)
  Console.WriteLine(Math.Round(1M, x));      // 1   (would like 1.000)
  Console.WriteLine(Math.Round(1.2M, x));    // 1.2 (would like 1.200)
  </code></pre>
  
  <p>Note that since I want to control the number of places programatically, this string.Format won't work (surely I ought not generate the format string):</p>
  
  <pre><code>Console.WriteLine(
      string.Format("{0:0.000}", 1.2M));    // 1.200 (good)
  </code></pre>
  
  <p>Should I just include Microsoft.VisualBasic and use <a href="http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.strings.formatnumber(VS.80).aspx" rel="noreferrer">FormatNumber</a>?</p>
  
  <p>I'm hopefully missing something obvious here.</p>