How do I format a Decimal to a programatically controlled number of decimals in c#?

Try

decimal x = 32.0040M;
string value = x.ToString("N" + 3 /* decimal places */); // 32.004
string value = x.ToString("N" + 2 /* decimal places */); // 32.00
// etc.

Hope this works for you. See

http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

for more information. If you find the appending a little hacky try:

public static string ToRoundedString(this decimal d, int decimalPlaces) {
    return d.ToString("N" + decimalPlaces);
}

Then you can just call

decimal x = 32.0123M;
string value = x.ToRoundedString(3);  // 32.012;

Leave a Comment