How do I display a decimal value to 2 decimal places?

When displaying the value of a decimal currently with .ToString(), it's accurate to like 15 decimal places, and since I'm using it to represent dollars and cents, I only want the output to be 2 decimal places.

Do I use a variation of .ToString() for this?


Solution 1:

decimalVar.ToString("#.##"); // returns ".5" when decimalVar == 0.5m

or

decimalVar.ToString("0.##"); // returns "0.5"  when decimalVar == 0.5m

or

decimalVar.ToString("0.00"); // returns "0.50"  when decimalVar == 0.5m

Solution 2:

I know this is an old question, but I was surprised to see that no one seemed to post an answer that;

  1. Didn't use bankers rounding
  2. Keeps the value as a decimal.

This is what I would use:

decimal.Round(yourValue, 2, MidpointRounding.AwayFromZero);

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

Solution 3:

decimalVar.ToString("F");

This will:

  • Round off to 2 decimal places eg. 23.45623.46
  • Ensure that there are always 2 decimal places eg. 2323.00; 12.512.50

Ideal for displaying currency.

Check out the documentation on ToString("F") (thanks to Jon Schneider).

Solution 4:

If you just need this for display use string.Format

String.Format("{0:0.00}", 123.4567m);      // "123.46"

http://www.csharp-examples.net/string-format-double/

The "m" is a decimal suffix. About the decimal suffix:

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