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

1,252,416

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

Solution 5

Given decimal d=12.345; the expressions d.ToString("C") or String.Format("{0:C}", d) yield $12.35 - note that the current culture's currency settings including the symbol are used.

Note that "C" uses number of digits from current culture. You can always override default to force necessary precision with C{Precision specifier} like String.Format("{0:C2}", 5.123d).

Share:
1,252,416
Timur Zanagar
Author by

Timur Zanagar

Software Craftsman based in Auckland, New Zealand.

Updated on February 14, 2022

Comments

  • Timur Zanagar
    Timur Zanagar about 2 years

    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?