2012-11-08 52 views
7

可能重複:
Using String Format to show decimal upto 2 places or simple integer
How to set decimal point in 2 decimal places?如何在mvc3,C#中將數字顯示爲2位小數?

我有我的看法價格區域。它具有以下值2.5 and 44. 我想顯示此值2.50 and 44.00我使用下面的代碼

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

其中item.OtherFields["price"] is a object我將其轉換爲字符串,然後十進制

但Math.round沒有工作,那麼顯示2.5,只有44 .. 誰能幫助這個

+0

爲什麼標題說 「整」? –

+0

你可以按照這個帖子: http://stackoverflow.com/questions/6951335/using-string-format-to-show-decimal-upto-2-places-or-simple-integer –

+0

HTTP:/ /stackoverflow.com/questions/5428289/mvc3-decimal-truncated-to-2-decimal-places-on-edit – alexsuslin

回答

24

Math.Round就是這樣 - 圓。

要格式化您可以使用.ToString(formatString)像這樣的數字:

item.OtherFields["price"].ToString("0.00") 
+0

沒有ToString的重載方法需要1個參數 – niico

+1

@niico你可能調用了可以爲null的類型的ToString 。如果是這樣,你必須做'youVariable.Value.ToString(「0.00」)'。不要忘記首先檢查空! – PeteGO

4

這應該爲你

yourvalue.ToString ("0.00"); 
工作
3
decimal dValue = 2.5; 
string sDisplayValue = dValue.ToString("0.00"); 
12

使用字符串格式功能

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 
*/ 
相關問題