简体   繁体   中英

Converting a decimal data type value to a formatted string

I want to convert the results of Label22.Text and Label21.Text to a number with two decimal places. Have tried a number of variations

sda = new SqlDataAdapter(@"SELECT fname, SUM([debit]/1.2) AS [D], SUM([credit]/1.2) AS [C] FROM detail GROUP BY fname", con);
DataSet ds = new DataSet();
sda.Fill(ds);
DataRow dr = ds.Tables[0].Select("fname = '0092632'").FirstOrDefault();

if (dr != null)
{
    Label22.Text = dr["D"].ToString();
    Label21.Text = dr["C"].ToString();
}

Try this

Label22.Text = string.Format("{0:N2}", Convert.ToDecimal(dr["D"].ToString()));
Label21.Text = string.Format("{0:N2}", Convert.ToDecimal(dr["C"].ToString()));

Also try this

Label22.Text = string.Format("{0:0.00}", dr["D"].ToString());
Label21.Text = string.Format("{0:0.00}", dr["C"].ToString());

You can also do it in your query:

SELECT 
    fname, 
    CONVERT(DECIMAL(20,2), SUM([debit]/1.2)) AS [D], 
    CONVERT(DECIMAL(20,2), SUM([credit]/1.2)) AS [C] 
FROM 
    detail 
GROUP BY 
    fname

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM