Hugo Woesthuis
Hugo Woesthuis

Reputation: 193

How can I use 2 decimals using money in ASP.NET web forms?

I know, there are a few answers here, but neither of them works.

So here is the scenario:

Got a GridView and in one of these columns, a price is declared. In the SQL Database, I use money to declare the price. The GridView will import the data from the database programmatically Code here:

        var con = new SqlConnection();
        var cmd = new SqlCommand();
        var dt = new DataTable();
        con.ConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\hugow\Documents\Visual Studio 2015\Projects\OSGS_v2\dataBase.mdf;Integrated Security=True;Connect Timeout=30";
        cmd.Connection = con;
        string cmdText = null;
        string usrName = Request.Cookies["usrData"]["usrName"];
        cmdText = "SELECT orderID, Products, orderPrice, date FROM orderData WHERE orderUser=@usr";
        cmd.Parameters.Add("@usr", SqlDbType.VarChar).Value = usrName;
        con.Open();
        cmd.CommandText = cmdText;
        var da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        stdT.DataSource = dt;
        stdT.DataBind();
        con.Close();
        con.Dispose();

And I want to show the price as a two decimal price (0,00). The problem is: It shows 4 decimals (0,0000).

2 Questions:

  1. How to show 2 decimals instead of 4?
  2. Why does money have 4 decimals instead of 2?

I use Web Forms, not MVC.

Thanks in advance!

Upvotes: 0

Views: 1018

Answers (2)

VDWWD
VDWWD

Reputation: 35514

If you use <ItemTemplate> you can use this:

<%# string.Format("{0:c}", Convert.ToDecimal(Eval("orderPrice"))) %>

With BoundField you use DataFormatString:

<asp:BoundField DataField="orderPrice" HeaderText="Price" DataFormatString="{0:c}" />

0:c will give you the correct currency format with the corresponding money symbol for your current localization. If you want a numeric value with 2 decimals you would use 0:N2.

For all format options see https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx

Upvotes: 1

Robin
Robin

Reputation: 76

Just tell your system to wrap the value to two decimals,

decimal.Round("your value", 2, MidpointRounding.AwayFromZero);

Upvotes: 1

Related Questions