16

Possible Duplicate:
Using String Format to show decimal upto 2 places or simple integer
How to set decimal point in 2 decimal places?

I have Price field in my view. it have the following values 2.5 and 44. I want to display this value to 2.50 and 44.00 i use the following code

@{decimal prolistprice = decimal.Parse(item.OtherFields["Price"].ToString());}
  $@Math.Round(prolistprice, 2, MidpointRounding.AwayFromZero)

in which item.OtherFields["price"] is a object i convert it to string and then decimal

but Math.round is not working it shows 2.5 and 44 only.. Can anyone help this

Community
  • 1
  • 1
Prakash
  • 235
  • 1
  • 2
  • 13

4 Answers4

38

Math.Round does just that - round.

To format the number you may use .ToString(formatString) like so:

item.OtherFields["price"].ToString("0.00")
PeteGO
  • 5,350
  • 3
  • 36
  • 66
  • 1
    No overload method for ToString takes 1 argument – niico Jan 31 '18 at 22:25
  • 3
    @niico you're probably calling `ToString` on a nullable type. If so, you'll have to do `youVariable.Value.ToString("0.00")`. Don't forget to null check first though! – PeteGO Feb 01 '18 at 21:25
13

Use string format function

1. string.Format("{0:n2}", 200000000.8776);
2. string.Format("{0:n3}", 200000000.8776);
3. string.Format("{0:n2}", 0.3);

/* OUTOUT
1. 200,000,000.88
2. 200,000,000.878
3. 0.30
*/
Naresh Pansuriya
  • 2,028
  • 12
  • 14
4

This should work for you

yourvalue.ToString ("0.00");
KroaX
  • 5,625
  • 4
  • 29
  • 41
3
decimal dValue = 2.5;
string sDisplayValue = dValue.ToString("0.00");
Lawrence Johnson
  • 3,804
  • 2
  • 15
  • 28