2

I have a decimal with value "2.2", what i need is "2.20".

I have tried

String.Format("0:0.00",decimalVar);

and

decimal.Round(decimalVar,2,MidpointRounding.AwayFromZero)

and

Math.Round(decimalVar,2)

But they are all returning the original "2.2" value. There are plenty of answers for this question but they are all about "How to limit digits to two if they are more than two".

I need to show two digits when there is only one digit.

1
  • can you show the code printing the result of String.Format("0:0.00",decimalVar); because it should work
    – Astra Bear
    Commented Feb 20, 2015 at 6:41

5 Answers 5

3

It's a simple typo, your first line should be:

String.Format("{0:0.00}", decimalVar)

Note the braces. Alternatively, you can use

decimalVar.ToString("0.00")

Why rounding doesn't fix your problem:

Mathematically, 2.2 is exactly the same as 2.20, so Round won't change anything. The only thing that matters here is how you format the mathematical value into a decimal string. Thus, String.Format and ToString(someFormatString) are the correct choices here.

2

change:

String.Format("0:0.00",decimalVar);

to:

String.Format("{0:0.00}",decimalVar);

a working fiddle of your example

1

you can use ToString

decimalVar.ToString("0.00")

or String.Format

string.Format("{0:0.00}",decimalVar));
1

If you want 2 digits after decimal point in the string representation, just format it out (F2 in your case):

  Decimal value = 2.2M;
  String result = value.ToString("F2"); // 2.20

Other possible formats you may find useful:

 0.00
 0.#0
 #.#0

Note, that Math says that 2.2 == 2.20 that's why Round() is not a way out.

0

use below code snap

DecimalFormat format = new DecimalFormat("0.00");
    format.format(decimal);

Not the answer you're looking for? Browse other questions tagged or ask your own question.