How to convert reader.Read string to currency format in c#?

Viewed 717

I built the below code, trying to convert reader[BalanceAmt] to a currency, i.e. $23,456.78. I can't seem to get it to work. It's still returning "23456.782" Any ideas?

    while (reader.Read())
                    {
                        string MyNum = reader["BalanceAmt"].ToString();
                        String.Format("{0:#,###0}", MyNum);
                        BalanceBox.Text = (MyNum);

                    }
3 Answers

If reader["BalanceAmt"] returns a string then to get your numeric formatting to work, you need to convert it into a number before converting it to currency - i.e.

var myNum = Convert.ToDecimal(reader["BalanceAmt"]);
BalanceBox.Text = myNum.ToString("C");

Note the "C" currency format specifier argument passed into the decimal.ToString method - see MSDN Decimal.ToString Method Documentation.

The Convert.ToDecimal method will throw an exception if reader["BalanceAmt"] contains anything that Convert.ToDecimal is unable to cope with (non-numeric characters).

You might want to put a try..catch around this, or if you don't want an exception to be thrown, use Decimal.TryParse inside an if check:

var balanceAmt = reader["BalanceAmt"];

if (decimal.TryParse(balanceAmt, out var myNum))
{
    BalanceBox.Text = myNum.ToString("C");
}
 while (reader.Read())
   {
     BalanceBox.Text = reader["BalanceAmt"].ToString("c");
   }

In your code String.Format("{0:#,###0}", MyNum); MyNum never changes...only formatted.

Please use this:

BalanceBox.Text = String.Format("{0:#,###0}", Convert.ToDouble(MyNum));
Related