Two Decimal places using c#

decimal Debitvalue = 1156.547m;


decimal DEBITAMT = Convert.ToDecimal(string.Format("{0:0.00}", Debitvalue));

I have to get only two decimal places but by using this code I am getting 1156.547. Let me know which format I have to use to display two decimal places.

356372 次浏览

Use Math.Round() for rounding to two decimal places

decimal DEBITAMT = Math.Round(1156.547m, 2);

If you want to round the decimal, look at Math.Round()

here is another approach

decimal decimalRounded = Decimal.Parse(Debitvalue.ToString("0.00"));

Your question is asking to display two decimal places. Using the following String.format will help:

String.Format("{0:.##}", Debitvalue)

this will display then number with up to two decimal places(e.g. 2.10 would be shown as 2.1 ).

Use "{0:.00}", if you want always show two decimal places(e.g. 2.10 would be shown as 2.10 )

Or if you want the currency symbol displayed use the following:

String.Format("{0:C}", Debitvalue)

Another option is to use the Decimal.Round Method

I use

decimal Debitvalue = 1156.547m;
decimal DEBITAMT = Convert.ToDecimal(string.Format("{0:F2}", Debitvalue));

Another way :

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

Probably a variant of the other examples, but I use this method to also make sure a dot is shown before the decimal places and not a comma:

someValue.ToString("0.00", CultureInfo.InvariantCulture)

The best approach if you want to ALWAYS show two decimal places (even if your number only has one decimal place) is to use

yournumber.ToString("0.00");

For only to display, property of String can be used as following..

double value = 123.456789;
String.Format("{0:0.00}", value);

Using System.Math.Round. This value can be assigned to others or manipulated as required..

double value = 123.456789;
System.Math.Round(value, 2);

If someone looking for a way to display decimal places even if it ends with ".00", use this:

String.Format("{0:n1}", value)

Reference:

https://learn.microsoft.com/pt-br/dotnet/standard/base-types/standard-numeric-format-strings#the-numeric-n-format-specifier

In some tests here, it worked perfectly this way:

Decimal.Round(value, 2);

Hope this helps

To display two decimal digits, try the given syntax.

string.Format("{0:0.00}", Debitvalue)