I built the below code, trying to convert reader[BalanceAmt] to a currency, ie $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);
}
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 - ie
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.
请使用:
BalanceBox.Text = String.Format("{0:#,###0}", Convert.ToDouble(MyNum));
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.