如何在 C# 中显示货币格式
本文关键字:显示 货币 格式 | 更新日期: 2023-09-27 18:33:47
嗨,我在使用这种格式显示金额时遇到问题:0,000.00 。我正在使用网格视图和数据读取器来显示 mySQL 数据库中的金额,十进制作为我的数据类型,我的输出仅显示 0000.00
你能帮我如何解决这个问题吗?谢谢。
private void DisplayOrderDetails(int nOrderNo)
{
OpenConnection();
SqlCommand cmdSelect = new SqlCommand();
cmdSelect.Connection = cn;
cmdSelect.CommandType = CommandType.Text;
cmdSelect.Transaction = trnOrder;
cmdSelect.CommandText =
"SELECT OrderDetailNo, OrderNo, PackagingOutside, Quantity, Unit, ProductNo, ProductName, " +
"ProductSize, PackagingInside, " +
"SellingDiscount1, SellingDiscount2, SellingDiscount3, SellingDiscount4, " +
"SellingPrice, Amount FROM OrderDetails WHERE OrderNo = '"
+ nOrderNo + "'";
SqlDataAdapter daDetail = new SqlDataAdapter();
daDetail.SelectCommand = cmdSelect;
DataSet ds = new DataSet();
daDetail.Fill(ds, "OrderDetails");
grdDetails.DataSource = null;
grdDetails.DataSource = ds.Tables["OrderDetails"];
DisplayTotal();
}
private void DisplayTotal()
{
double dTotal = 0;
//for encountering errors in the future
try
{
for (int nRow = 0;
nRow <= dsDetail.Tables["OrderDetails"].Rows.Count - 1;
nRow++)
{
dTotal = dTotal +
Convert.ToDouble(dsDetail.Tables["OrderDetails"].Rows[nRow]["Amount"].ToString());
}
}
catch //(Exception ex)
{
//MessageBox.Show(ex.Message);
}
lblTotal.Text = String.Format("{0:#,###,##0.00}", dTotal);
}
对于货币或货币格式,您需要使用C
因此将您的代码更改为
lblTotal.Text = dTotal.ToString("C", CultureInfo.CurrentCulture);
或
lblTotal.Text = String.Format("{0:C}", dTotal);
参考
lblTotal.Text = dTotal.ToString("C");
不要忘记,这使用默认的区域性信息并显示默认货币。还可以通过提供CultureInfo
的实例来更改此行为
http://msdn.microsoft.com/en-us/library/shxtf045.aspx
您可以使用
CultureInfo 对象并将目标区域性传递给 String.Format
,然后这将使用正确的区域性信息显示货币和其他字符串:
var cultureInfo = System.Globalization.CultureInfo.CreateSpecificCulture("de-DE"); // for example, the German culture info will give you the commas for thousand separators instead of the decimal point
lblTotal.Text = String.Format(cultureInfo, "{0:C}", dTotal);
CultureInfo.CreateSpecificCulture
参考 : http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.createspecificculture.aspx上述String.Format
重载的参考:http://msdn.microsoft.com/en-us/library/1ksz8yb7.aspx
本节可能值得从String.Format
文档中阅读:http://msdn.microsoft.com/en-us/library/system.string.format.aspx#Format_Culture