如何使用C#将十进制转换为字符串

时间:2015-02-21 16:16:25

标签: c# asp.net sql-server

我从我的数据库中得到一些小数结果,但我想将其转换为字符串。从数据库返回的值类似于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();
    }
}

3 个答案:

答案 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()方法。

以下是standard numeric format规则和custom numeric formatting规则。