Jason
Jason

Reputation: 87

How to convert sql nvarChar to formatted decimal

I am pulling a value off of the database which is of type nvarchar. My C# program is attempting to format the value but it's not working.

    string paymentAmount = null;

    if (dbDataReader["Amount"] != DBNull.Value)
    {
     paymentAmount = string.Format("{0:0,0.00}", dbDataReader["Amount"]).TrimStart('0');
    }

The data on the database looks like this:

Amount 
0017168

After the above code executes the number is 17168. How can I format this number to be 171.68 ?

Upvotes: 0

Views: 215

Answers (1)

Gabriel Negut
Gabriel Negut

Reputation: 13960

var amount = decimal.Parse(dbDataReader["Amount"]) / 100;
paymentAmount = string.Format("{0:0,0.00}", amount);

Ideally you would store the amount as a numeric value instead of string, but if that's not possible, add some exception handling to make sure it does not blow up at runtime.

Upvotes: 1

Related Questions