Hugo Woesthuis Hugo Woesthuis - 8 months ago 32
ASP.NET (C#) Question

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

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;
cmd.CommandText = cmdText;
var da = new SqlDataAdapter(cmd);
stdT.DataSource = dt;

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
    have 4 decimals instead of 2?

I use Web Forms, not MVC.

Thanks in advance!


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