iuliko
iuliko

Reputation: 73

Formatting currency from string session in c#

Hello I am having difficulty with a web application. I am almost done but I am tripping up on this issue. So with this web application, there is another page that shows gets input from the user for a sales price and discount amount and then gets a total price from the sales price - discountamount. I finally got the second page (where this code is from) to grab the session string values but I need to format these correctly into currency. I copied the code from the first page in the commented out part to try to analyze it but I am at a loss and would appreciate the help as I am almost done.

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");
    }
}

Upvotes: 0

Views: 772

Answers (1)

Josh Greenberg
Josh Greenberg

Reputation: 323

If you need to convert the values in the session to currencies, you could to something like this:

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");

If you're absolutely sure the session values exist, you don't need to check for null. You can read more about Standard Numeric Formatting here: https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx.

I hope this helps.

Upvotes: 1

Related Questions