2017-02-28 22 views
0

你好,我有一個Web應用程序的困難。我差不多已經完成了,但我正在解決這個問題。因此,通過這個Web應用程序,還有另一個頁面顯示來自用戶的銷售價格和折扣金額的輸入,然後從銷售價格 - 折扣金額中獲得總價格。我終於得到第二頁(代碼來自這裏)獲取會話字符串值,但我需要將這些正確格式化爲貨幣。我從註釋部分的第一頁複製了代碼,嘗試分析它的代碼,但是我很茫然,因爲我差不多完成了,所以我會很感激這些幫助。從C中的字符串會話格式化貨幣#

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 

public partial class Confirm : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     //int salesPrice, discountAmount, totalPrice; 
     UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None; 
     if (Session["salesprice"] != null && Session["discountamount"] != null && Session["totalprice"] != null) 
     { 
      lblSalesPrice.Text = Session["salesprice"].ToString(); 

      lblDiscountAmount.Text = Session["discountamount"].ToString(); 
      lblTotalPrice.Text = Session["totalprice"].ToString(); 

      /* 
      decimal salesPrice = Convert.ToDecimal(txtSalesPrice.Text); 
      decimal discountPercent = Convert.ToDecimal(txtDiscountPercent.Text)/100; 

      decimal discountAmount = salesPrice * discountPercent; 
      decimal totalPrice = salesPrice - discountAmount; 

      lblDiscountAmount.Text = discountAmount.ToString("c"); 
      lblTotalPrice.Text = totalPrice.ToString("c");*/ 

     } 
    } 
    protected void Button1_Click(object sender, EventArgs e) 
    { 
     lblMessage.Text = "This function hasn't been implemented yet."; 
    } 
    protected void Button2_Click(object sender, EventArgs e) 
    { 
     Server.Transfer("Default.aspx"); 
    } 
} 
+0

我一定會錯過一些東西,因爲我不太明白你有什麼問題或最終目標是什麼。你問如何將字符串轉換爲貨幣或完全不同的東西? –

+0

這就是我所要求的。我現在已經正常工作了。 – iuliko

回答

1

如果您需要將這些值轉換在會話中的貨幣,你可以到這樣的事情:

if (Session["salesprice"] != null) 
    lblSalesPrice.Text = Convert.ToDouble(Session["salesprice"]).ToString("c"); 

if (Session["discountamount"] != null) 
    lblDiscountAmount.Text = Convert.ToDouble(Session["discountamount"]).ToString("c"); 

if (Session["totalprice"] != null) 
    lblTotalPrice.Text = Convert.ToDouble(Session["totalprice"]).ToString("c"); 

如果你是絕對肯定的會話值存在,你不需要檢查爲空。您可以在這裏閱讀有關標準數字格式的更多信息:https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx

我希望這會有所幫助。

+0

謝謝!它非常有幫助。所以我猜我缺少的是.ToString(「c」)並將字符串轉換爲double。爲了確保我理解正確,會話值保存爲字符串「c」,我從前一頁調用它們,對吧?以及上一頁的格式?我猜這是因爲它顯示的貨幣從會話值中顯示出來。 – iuliko

+0

「c」代表貨幣。所以你拿了一個數字(在這種情況下是雙倍數)並且作爲「貨幣」呈現。這種方式.NET將數字格式化爲應用程序的文化。對於不同的文化,它會變得非常有趣,因爲.NET知道如何正確格式化爲美元,歐元,日元等。至於價值如何存儲在會話中,我無法從您發佈的代碼中分辨出來。如果我的回答正確回答你的問題,請接受答案。 –