【问题标题】:Show database value(float) to C# in label as float or double?在标签中将数据库值(浮点数)显示为浮点数或双精度数?
【发布时间】:2018-03-09 16:17:06
【问题描述】:

如何在标签中将数据库值(浮点数)显示为浮点数或双精度值?我已经弄清楚如何将其显示为字符串,但无法使其显示为双精度。我试过.ToString("00.00)";.ToString("#0.00"); 并得到一个错误“方法'To String' 没有重载需要1 个参数。”。

private void pos_Load(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection("Data Source=DESKTOP-39SPLT0;Initial Catalog=SalesandInventory;Integrated Security=True");
            con.Open();
            SqlCommand cmd1 = new SqlCommand("select * from tblProduct", con);
            SqlDataReader reader = cmd1.ExecuteReader();
            reader.Read();
            lblEspSing.Text = reader["pPrice"].ToString();
            reader.Read();
            lblEspDou.Text = reader["pPrice"].ToString();
        }        

【问题讨论】:

  • reader["pPrice"] 只返回一个对象,您需要将其转换为正确的类型(并注意空值)

标签: c# .net sql-server ado.net


【解决方案1】:

你需要先施放它

((float) reader["pPrice"]).ToString("00.00"); 

【讨论】:

  • 好收获。只需像这样修复它ToString("00.00") 以便它编译。
  • 我收到错误“InvalidCastException 未处理”并且 lblEspSing 以蓝色突出显示。我不知道高亮表示抱歉。
  • @S.Akbari 已修复
  • @ChresAbte 检查您的数据库类型。如果它是一个浮点数,这应该可以工作。如果它是双精度(真实(53)),那么您需要将其转换为双精度。如果它是一个 varchar 那么你需要做字符串格式
  • 浮动在我的数据库@Steve
【解决方案2】:

您可以将其转换为字符串,然后在其上使用 string.format,使用 {0:N2}。 格式化为两位小数。

string.Format("{0:N2}", pPrice)

那么如果你需要 3 位小数:

string.Format("{0:N3}", pPrice)

等等。

您也可以通过这种方式将值存储在字符串中,而无需担心精度,然后将您要测试的值转换为字符串进行比较:

string strDecimalVal = Convert.ToString(pPrice);

【讨论】:

  • 对不起,我不知道该放在哪里。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-30
  • 1970-01-01
  • 2015-06-12
  • 2012-04-15
  • 1970-01-01
  • 2022-11-19
  • 2020-02-03
相关资源
最近更新 更多