我从我的数据库中得到一些小数结果,但我想将其转换为字符串。从数据库返回的值类似于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();
}
}
答案 0 :(得分:2)
您只需要调用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
,因为您在使用块中,它会自动执行此操作。不过,你应该拨打Close
。
答案 1 :(得分:0)
使用此代码将十进制值转换为字符串:
num.ToString( "0.#" )
答案 2 :(得分:0)
如果您希望更好地控制decimal
如何以字符串格式表示,请使用String.Format()
方法。