我从数据库中得到一些小数结果,但我想将其转换为字符串。从数据库返回的值是2.500000或1.500000,但在此示例中,我想将其显示为2.5或1.5
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = @"select DATEDIFF(minute, Min(myDate), Max(myDate)) / 60.0 as hours
from myTable
where userid = @UserID
and DT_Submitted = (select CAST(FLOOR( CAST(GETDATE() AS FLOAT)) AS DATETIME))
and Checked = 1";
cmd.Parameters.AddWithValue("@UserID", tempUser.ToString());
con.Open();
decimal result = (decimal)cmd.ExecuteScalar();
lblHours.Text = result.ToString() + " Hours";
con.Close();
con.Dispose();
}
}
您只需要调用其中一个ToString
接受格式字符串的重载即可。
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = @"select DATEDIFF(minute, Min(myDate), Max(myDate)) / 60.0 as hours
from myTable
where userid = @UserID
and DT_Submitted = (select CAST(FLOOR( CAST(GETDATE() AS FLOAT)) AS DATETIME))
and Checked = 1";
cmd.Parameters.AddWithValue("@UserID", tempUser.ToString());
con.Open();
decimal result = (decimal)cmd.ExecuteScalar();
lblHours.Text = result.ToString("0.#") + " Hours";
con.Close();
}
}
附带一提,您不需要调用Dispose
连接,因为您处于using块中,该块会自动进行连接。不过,您应该致电Close
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句